jQuery ajax - getJSON() method
Example
Use AJAX requests to obtain JSON data and output the results:
$("button").click(function(){ $.getJSON("demo_ajax_json.js",function(result){ $.each(result, function(i, field){ $("div").append(field + " "); ); ); );
Definition and Usage
Load JSON data via HTTP GET request.
In jQuery 1.2, you can load JSON data from other domains using JSONP-style callback functions, 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 the callback function is executed.
Syntax
jQuery.getJSON(url,data,success(data,status,xhr)})
Parameter | Description |
---|---|
url | Required. Specifies which URL the request is to be sent to. |
data | Optional. Specifies the data to be sent along with the request to the server. |
success(data,status,xhr)} |
Optional. Specifies a function to be executed when the request is successful. Additional Parameters:
|
Detailed Explanation
This function is a shorthand Ajax function, equivalent to:
$.ajax({ url: url, data: data, success: callback, dataType: json );
The data sent to the server can be attached to the URL after the query string. If data If the value of the parameter is an object (mapping), it will be converted to a string and URL-encoded before being attached to the URL.
Passed to callback The returned data can be a JavaScript object or an array defined with JSON structure, and parsed using the $.parseJSON() method.
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); );
More Examples
Example 1
Load 4 of the latest photos about cats from the 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, add parameters, and display a name field data in the JSON data:
$.getJSON("test.js", { name: "Bill", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); );