New to Ajax calls. Need some pointers to start my learning but want to do it with a real example.
This link: http://api.tumblr.com/v2/blog/david.tumblr.com/info?api_key=API_KEY
returns this to my browser which is a good example of data I’ll be using:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "David\u2019s Log",
"posts": 3981,
"name": "david",
"url": "http:\/\/www.davidslog.com\/",
"updated": 1348785660,
"description": "\u201cMr. Karp is tall and skinny, with unflinching blue eyes and a mop of brown hair. He speaks incredibly fast and in complete paragraphs.\u201d \u2013 NY Observer",
"ask": false
}
}
}
I think I could use this as a start but definitely open to other ways:
var tumblrURL = "david.tumblr.com";
jQuery.ajax({
url: "http://api.tumblr.com/v2/blog/" + tumblrURL + "/info",
data: {api_key: "MY_PRIVATE_API_KEY"},
dataType: "jsonp",
});
But I am lost as to proper ways to parse out and get the different bits returned and use them as vars or for tests in the call.
For example, how do I get “status” or the “name”?
When the status is a 200 then I would want to make a var out of the name (“david”) and use it for other options.
Or, if the status is a 404 then I would want to do something else (like return an error).
Please, no flames. I’m trying to learn and if I get a few examples or pointers I will be able to move on to more interesting stuff. I’m OK with other aspects of jQuery so those issues should be fine.
Thanks!
The
jQuery.Ajaxfunction takes an optional function parametersuccess:You could set this to your own function, which would automatically execute once the request succeeds – providing you with the entire JSON blob you receive as a normal Javascript object. In your case, you could get the status of the request at
data.meta.status– or the name atdata.response.blog.name.Note that jQuery also allows for error handlers on Ajax requests, called automatically in a similar way:
error(jqXHR, textStatus, errorThrown).Example code: