This article mainly introduces the getJSON () usage instance in jQuery + ajax. If you need it, refer to the following example:
Load JSON data from test. js and display a name field in JSON data:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name);});
Definition and usage
Load JSON data using http get requests.
In jQuery 1.2, you can use a callback function in the form of JSONP to load JSON data of other domains, such as "myurl? Callback =? ". Will jQuery be replaced automatically? For the correct function name to execute the callback function. Note: The Code after this row will be executed before the callback function is executed.
Syntax
JQuery. getJSON (url, [data], [callback])
Parameter description
The url of the page to be loaded.
The Key/value parameter of the data to be sent.
The callback function executed when the callback is loaded successfully.
Detailed description
This function is short for Ajax functions and is equivalent:
$.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 (ing), it is converted to a string and URL encoded before being appended to the URL.
The returned 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 instances
Example 1
Load four latest pictures about cats from the Flickr jsonp api:
HTML code:
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){ $("").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; });});
Example 2
Load JSON data from test. js and add parameters to display a name field in JSON data:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name);});
For more information about getJSON () usage examples in jQuery + ajax, see the PHP Chinese website!