This article mainly introduces the getJSON () usage example in jQuery + ajax. For more information, see
Instance
Load JSON data from test. js and display a name field in JSON data:
The Code is as follows:
$. GetJSON ("test. js? 1.1.23 ", 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:
The Code is as follows:
$. 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:
The Code is as follows:
JQuery code:
The Code is as follows:
$. 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:
The Code is as follows:
$. GetJSON ("test. js? 1.1.23 ", {name:" John ", time:" 2 "}, function (json ){
Alert ("JSON Data:" + json. users [3]. name );
});