Example of getJSON of usage in jQuery+ajax
- 2020-05-09 18:05:56
- OfStack
The instance
Load JSON data from test.js and display 1 name field data from JSON data:
$.getJSON("test.js", function(json){
alert("JSON Data: " + json.users[3].name);
});
Definition and usage
Load JSON data with HTTP GET request.
In jQuery 1.2, you can load JSON data for other domains by using a callback function in the form of JSONP, such as "myurl? callback = & # 63;" . jQuery will be replaced automatically. Is the correct function name to execute the callback function. Note: code following this line will be executed before the callback function is executed.
grammar
jQuery.getJSON(url,[data],[callback])
The parameter is described
The URL address of the url page to load.
data to send Key/value parameters.
callback callback function executed on successful load.
Detailed instructions
This function is the Ajax function, which is equivalent to:
$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});
The data sent to the server can be appended to URL as a query string. If the value of the data parameter is an object (map), it will be converted to a string and URL encoded before attaching to URL.
The returned data passed to callback can be an JavaScript object or an array defined in the JSON structure and parsed using the $.parseJSON () method.
More instances
Example 1
Load 4 latest cat pictures from Flickr JSONP API:
HTML code:
<div id="images"></div>
jQuery code:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?
tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
Example 2
Load JSON data from test.js, attach parameters, display 1 name field data in JSON data:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
alert("JSON Data: " + json.users[3].name);
});