I have a problem. I built a script to make a request to an internal link that sends back a response. This is what the script looks like:
jQuery.get(callUrl, function(data) {
console.log(typeof data);
jQuery.each(data.items, function(i, item) {
console.log(i);
});
}, 'json');
and the response that the server sends back looks like this:
{"items":[
{
"src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
"id": "83",
"gallery_id": "30",
"username": "admin"
}]
}
My problem is when I parse the "data" its type is always string. I need for it to be an object so that I can query it and parse it with my script. To get to the bottom of the problem, I've tried comparing my script to the example on jQuery's documentation page:
http://docs.jquery.com/Ajax/jQuery.getJSON
The main differences with the request on this page and my request is that it uses the getJSON method. When I tried to use that with the url to my server, I have gotten no response at all, so that is the main reason I opted for the get method, and specifying the return type as "json."
Another thing I tried: I checked out the Flickr feed that the jQuery example uses to look for the Content-type header that it sends back, thinking maybe my feed had the wrong header, and it is this on the Flickr feed:
Content-Type application/x-javascript; charset=utf-8
This is exactly the same header on my own feed. So I am puzzled. Does anyone know why this is happening?
The JSON needs to have brackets around it, so it should be:
({"items":[
{
"src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
"id": "83",
"gallery_id": "30",
"username": "admin"
}]
})
You should then be able to use getJSON, as this is the easiest way to get the data as an object. However, you can also eval() the string and that will return an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With