Anders Metnik
Anders Metnik

Reputation: 6237

Http request, extracting the data

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?

Upvotes: 1

Views: 276

Answers (1)

davidethell
davidethell

Reputation: 12018

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.

Upvotes: 1

Related Questions