Question about using API requests with jQuery and accessing the json results
I'm here using some API from a website which returns a bunch of results in a json format, and I want to handle them inside a jQuery script..
I know it's easy!! but this is not the question ;)
the api format is like this (which returns the cities, or a city information)
http://api.XXX.com/cities/key=11111111
http://api.XXX.com/cities/2/key=111111111
and the returned results goes like this
[{"city_id":"57","country_id":"55","name":"\u0627\u0644\u0631\u064a\u0627\u0636","added_by":"118","addition_timestamp":"2007-07-03 04:28:16","latitude":"24.6819612050146","longitude":"46.7234802246094","zoom":"10","top_user_ids":"3690,235,47,562,324"},{"city_id":"61","country_id":"55","name":"\u062c\u062f\u0629","added_by":"118","addition_timestamp":"2007-07-03 04:52:32","latitude":"21.5399566230854","longitude":"39.1827392578125","zoom":"10","top_user_ids":"3153,3613,293,3973,2510"},............... etc
The main problem is that I have no parameters to put them in the data sectio开发者_开发百科n in the get method, which means I can't access these data.
Here is my code, which is, unfortunately not working.
$.ajax({
type: 'GET',
url: 'http://api.XXX.com/cities/key=11111111',
dataType: 'json',
success: function(data){alert("okaay");}
});
Have you got an idea what to do to get the json data arrays one by one ?
you can pass data back to your server by specifying the data property of ajax as follows:
$.ajax({
type: 'GET',
url: 'cities/key=11111111', //look at the url here
data: {
city: 'London'
},
dataType: 'json',
success: function(data){alert("okaay");}
});
Now you can access this data on your server by how you normally access any querystring parameter thus depending on your server side implementation. Lemme know which lang you use and I will see if I can help you
btw if u need to use an absolute url and it is under a different domain/sub-domain you need to use jsonp as your datatype to avoid the cross side forgery attack restriction policy put in place by browsers.
please read jquerys ajax documentation for more details about the same
I hope I got your question correct. atleast this is what you stressed on in your bolded text
If you wanted to loop through the data returned you could do this (code not tested) -
$.ajax({
type: 'GET',
url: 'http://api.XXX.com/cities/key=11111111',
dataType: 'json',
success: function(data){
$.each(data, function(key, val) {
alert(key + "' - '" + val);
})
}
});
The problem might be that you are calling a server on a different domain: to do this you should use jsonp and set crossDomain to true. You could do (look at how you can access data in the success function);
$.ajax({
type: 'GET',
url: 'http://api.XXX.com/cities/key=11111111',
dataType: 'jsonp',
crossDomain: true,
success: function(data){
$.each(data, function(i, el){
alert(el.city)
});
;}
});
精彩评论