Here I have a code that I was playing around with.
It loads a string within my file and saves an unimportant one.
var file = "1";
var result;
var meString;
var splitMeString;
function preload() {
result = loadStrings("assets/save/"+file+".txt");
}
function setup() {
createCanvas(1000,650);
}
function draw() {
meString = result+'';
splitMeString = splitTokens(meString, ',');
text(meString,20,20);
console.log(splitMeString[2]);
}
function mousePressed(){
saveStrings("happy");
}
but how would I save a string to a specific location? Say I wanted to overwrite the file ("file")?
Questions like these are best answered by looking in the reference.
According to the reference, the saveStrings() function can take three arguments:
Syntax
saveStrings(list,filename,[extension])
Parameters
list String[]: string array to be written
filename String: filename for output
extension String: the filename's extension
So it sounds like you're looking for something like this:
saveStrings(yourArray, "file", "txt");
Also note that the third argument is optional, so this should also work:
saveStrings(yourArray, "file");
If you use the functions storeItem() and getItem() you can save strings to your program, this won't save it to a specific file embedded in your code but it will save it to your code. You can call whatever you stored in storeItem() with getItem()even after you close out of the tab. If you need any more info on it you can find it on the reference page here.
Hope this helps!
Related
It should be answer here but I can't find.
I have script like this:
for (count=1;count<5;count++) {
obj[count]=json[count]
}
Then I want connect this. But I made it manually:
objs=[...obj[1].posts,...obj[2].posts,...obj[3].posts,...obj[4].posts]
How I can automatically connect all this. Like this:
for (count=1;count<5;count++) {
obj[count]=json[count]
objs+=[...obj[count].posts]
}
Example:
var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];
Should get:
objs=[...obj[1],...obj[2]...obj[3]]
alert(objs)
Will result: 123,456,789
By using : filter & map
var obj=[];
var objs=[];
obj[1]=[123]
obj[2]=[456];
obj[3]=[789];
objs = obj.filter(Boolean).map(a=>a[0])
Sorry because I am dumb. I used objs,push(obj) with loop. Now I don't need loop of creating value. It now work well.
Script that I use now if you need:
obj=[]
for (count=1;count<5;count++) {
//Your script that gets json
...
//If your json is string (i don't know is every json in internet is string)
json=JSON.parse(json string that you get
obj.push(...json.posts) //You can change "posts" with array/object (I dont know what is this) that you want or without it if json is clean array
}
I am a beginner and using $.get to retrieve data from a rest API such as:
[{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},
{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}] }
$.get('http://xxxxxxxxxxx,
function (data) {
var obj = $.parseJSON(data);
So from what I understand I have retrieved the data from the REST API and parsed it so it is stored in a variable called obj.
My question is, how do I access and use each unique record in the obj variable?
Each record has it's own picture (item1.jpg, item2.jpg etc).
Whem my app loads I want it to show the item1.jpg image, and I want to be able to navigate to the other item pictures using buttons (previous / next).
I also want the description and price to be displayed underneath in some text input fields.
What I have figured so far is that I should:
Iterate through the obj variable, and store each record into an array.
Upon app initialisation I can set the default value for the image placeholder to array[index0].url, and set the description and price fields.
I can then set the previous and next buttons to array[currentIndex-1] or array[currentIndex+1].
Would this be the best way to do it?
Or can I just do this without using an array and manipulate the obj.data directly?
Thanks!!!
I may not be understanding what exactly what you want to do but I think I have the gist. If you just want to show the picture then the array of just images probably wouldn't be a bad idea. However, it looks like the Jason you're getting is already in an array. You can just use array index notation to get to what you want.
ie)
var arr = //your json response ;
var current = 0; //sets currently displayed object to the first in the array
var setCurrent = function () {
var image = arr[current]["url"];
}
You can then modify current however you want (on click on arrow iterate up/down, etc) then call the setCurrent function to set your image the the one you want. Hope that helps!
You can use the response you have from $.get() directly.
It is an array of objects.
You can use it like this:
console.log(data[2].description);
// outputs: "Console"
I've made a CodePen demo where it has a 4th object with a real image url to show you how to use the url info...
EDIT
Just in case you wouldn't know this:
You can use the response inside the scope of the $.get() callback...
You can not use it straith after the $.get() outside the callback since $.get() is asynchronous.
You can use it in some other handler wich will happen after the response is received.
var getResponse;
$.get('http://xxxxxxxxxxx', function (data) {
getResponse = data;
console.log(data[2].description);
// outputs: "Console"
console.log(getResponse[2].description);
// outputs: "Console"
});
console.log(getResponse[2].description);
// outputs: "Undefined"
// But since this handler will be triggered long after the response is obtained:
$("#somebutton").click(function(){
console.log(getResponse[2].description);
// outputs: "console"
});
In order for your page javascript to be able to access the data retrieved from your ajax request, you'll need to assign it to some variable which exists outside the callback function.
You will need to wait until the ajax request has been processed before you can read the array. So you might want to set the actual default image to be something that doesn't rely on the ajax request (a local image).
Here's a simple approach
// fake testing ajax func
function fakeget (url, callback) {
setTimeout(callback(JSON.stringify([
{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, {"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"},
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}
])), 1000);
}
// real code starts here
// global variables for ajax callback and setImg func to update
var imageData, currentImg;
// change this back to $.get for real
fakeget('http://xxxxxxxxxxx',
function (data) {
imageData = $.parseJSON(data);
setImg(0);
}
);
function setImg(index) {
// turns negative indices into expected "wraparound" index
currentImg = (index % imageData.length + imageData.length) % imageData.length;
var r = imageData[currentImg];
$("#theImg").attr('src', r.url);
$('#theDescription').text(r.price + " " + r.description);
}
$("#prev").click(function () {
setImg(currentImg - 1);
});
$("#next").click(function () {
setImg(currentImg + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id='theImg' src='somedefault.jpg'>
<div id='theDescription'></div>
</div>
<button id='prev'>Prev</button>
<button id='next'>Next</button>
Few observations :
Your JSON Object is not a valid JSON.
No need to parse it again your data is already a JSON Object.
Working fiddle
var data = [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}];
for (var i in data) {
var imgUrl = data[i].url;
console.log(imgUrl);
}
I would like to make my website(actually a web app) packaged into single file. I know a easiest way is to replace all path/url inside my code into data-url. But it will make the file hard to read by human. My idea is to use an array to store all data-url and write a function to obtain them by original url(as query string). It can also return the original url if nothing found.
Example:
store = new Array();
store.push({"url":"/img/icon.png","data-url":"dataurl:XXXXX"});
store.push({"url":"/img/icon1.png","data-url":"dataurl:XXXXX"});
function getResource(url) {
var result = url;
for(var row in store){
if (row.url == url) {
result = row.data-url;
}
}
return result;
}
So to use it, you also need a method to change the attribute in HTML element:
function replaceResource(e,attbName) {
e.target.setAttribute(attbName,getResource(e.target.getAttribute(attbName));
}
And in HTML:
<img src="/img/icon.png" onload="replaceResource(event,'src');" />
But I want to be simpler(since it's not good for human to read also). I want to override the DOM method for each type of HTMLElement(img,script etc.) by something like:
HTMLImageElement.prototype.src.callback = function (event) {
e.target.src = getResource(e.target.src);
}
So you don't need to do anything in HTML:
<img src="/img/icon.png" />
However the code for overriding native DOM method above is only my day-dream. I don't know what is correct syntax :'( Anybody can help?
Here is a reference to ADD custom method to native DOM element:
http://www.meekostuff.net/blog/Overriding-DOM-Methods/
On my web app, the user is asked a question and can choose only one of two answers. Yes or no. A query string is created based on their answer.
The following code carries the query string through the URL of every page:
var navlinks = document.getElementsByClassName("qString");
$(navlinks).prop("href", function() { return this.href + location.search; })
There are only 2 query strings, ?choice=yes and ?choice=no.
Once the user is taken through the app, if they navigate to either park01.html, park02.html, or park03.html from any other page, data will be pulled accordingly via a called function().
Here's my concept in pseudocode:
// I assume I should store specific html pages to a variable
var parkPages = ["park01.html", "park02.html", "park03.html”];
if (user clicks on specified html pages stored in variable) {
and the url contains = ?choice=yes;
Then call these functions: funcA(), funcB(), funcC();
}
else {
the url contains = ?choice=no;
Then call these functions: funcD(), funcE(), funcF();
}
Does the concept make sense? And what does the syntax look like?
If you're simply looking for a concrete translation of your pseudocode into JavaScript, based on your last comment, this should be what you need:
if (location.search === "?choice=yes") {
funcA();
funcB();
funcC();
}
else {
funcD();
funcE();
funcF();
}
Though at this stage, I'd recommend spending less time here and more on instructional/tutorial based websites.
I'm trying to use the Ajax File Upload as featured here: http://valums.com/ajax-upload/
As you can see, I need to create a qq.FileUploader object to initialize the script. However, I need to be able to dynamically create this objects without knowing the IDs of the elements. I've tried creating something like this:
var uploader, i = 0;
$(".file-upload").each(function() {
$e = $(this);
i++;
uploader[i] = new qq.FileUploader({
element: $(this)[0],
action: 'uploadfile.php',
allowedExtensions: ['doc', 'docx', 'pdf'],
multiple: false,
onComplete: function(id, fileName, responseJSON) {
$($e).siblings('input').val(responseJSON.newfilename);
}
});
});
I've learned that the [i] part I have added breaks the script, because I cannot have objects inside of an array.
Is there another way I can create this objects dynamically? They need to all have a unique name, otherwise the onComplete function gets overwritten for all of them. I experimented with using eval(), but I can't seem to make it work correctly.
You have to declare uploader as an array first :
var uploader = [];
Because you declared the variable without defining it, it has the default value of undefined , and your code was translated into something like undefined[i] which triggers an error.
Has to be something like
var uploader = {};
or else uploader is null and you cannot assign anything to it.
EDIT:
So there're two opitions, in my opinion, if one wants to have an array than it makes sense to declare one, var uploader = []; and then use the uploader.push() method or define it as an object var uploader = {}; and just do uploader[i] = ....
It is also possible to do the latter with an a array, but in the latter case I see no point in maintaining the counter (i).