I am new to json, js etc. So I am a bit confused about all this, httprequests etc. I am trying to extract data from a response. First I did the XMLHttpRequest, but I read here on Stackoverflow it is preferred to use a framework such as jquery or similar, and since I use jquery mobile already, that felt natural.
Now the question is how to get data out of the "response".
XMLHttpRequest.response text looks like this:
{"list":null,"data":{"id":95,"picture":"/content/picture/icons/Rome","text":"En galning hældte forleden 1 ton sukker i Roms officielle vandforsyning","appId":1,"textHeader":"Rome sweet Rome!!","localAction":"url(http://www.b.dk)","sortOrder":0,"lastCheck":null},"expires":2592000000,"server":null}
And now when I want to follow the example from jquery I get an object back. But nothing in the data.*
Their code:
var startUrl = "http://localhost:8080";
function httpGet(theUrl)
{
$.getJSON(startUrl+theUrl,
function(data){
alert(data);
$.each(data.items, function(i,item){
alert(i+item);
});
});
}
How to get my code out of it?
-
how do you get your code out of what exactly?shxfee– shxfee2012年07月03日 09:39:56 +00:00Commented Jul 3, 2012 at 9:39
-
1first off there is not .items in your response which is the reason you are not seeing anything.You can access the object properties using "data.*". Example to get id from the repsonse use: data.data.id;xdevel– xdevel2012年07月03日 09:45:03 +00:00Commented Jul 3, 2012 at 9:45
-
1this may help you.Jebin– Jebin2012年07月03日 09:49:53 +00:00Commented Jul 3, 2012 at 9:49
1 Answer 1
When you use getJSON the data result is automatically turned into a Javascript Object with properties matching the key values in the JSON string. So your object properties will be "list", "data", "expires" and "server".
The "data" property will be another object with the properties found in it like "id", "picture", "text", etc.
So to access your data just refer to it like an object:
var picture = data.data.picture;
var text = data.data.text;
Of course you don't need to put the values in vars like that. I'm just showing you how to reference them.