Example
Load JSON data from test.js and display a name field data in the JSON data:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });
Definition and usage
Load JSON data through HTTP GET request.
In jQuery 1.2, you can load JSON data from other domains by using a callback function in the form of JSONP, such as "myurl?callback=?". jQuery will automatically replace ? with the correct function name to execute the callback function. Note: The code after this line will be executed before this callback function is executed.
Syntax
jQuery.getJSON(url,[data],[callback])
Parameter Description
url The URL address of the page to be loaded.
data Key / value parameters to be sent.
callback Callback function executed when loading is successful.
Detailed description
This function is the abbreviated 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 the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and URL-encoded before being appended to the URL.
The return data passed to callback can be a JavaScript object or an array defined in a JSON structure, and is parsed using the $.parseJSON() method.
More examples
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, append parameters, and display a name field data in the JSON data:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); });
More jQuery +Please pay attention to the PHP Chinese website for related articles on getJSON() usage examples in ajax!