Home > Web Front-end > JS Tutorial > body text

Example of getJSON() usage in jQuery ajax_jquery

WBOY
Release: 2016-05-16 16:25:13
Original
1277 people have browsed it

Example
Load JSON data from test.js and display a name field data in the JSON data:

Copy code The code is as follows:

$.getJSON("test.js", function(json){
alert("JSON Data: " json.users[3].name);
});

Definition and usage
Load JSON data via HTTP GET request.

In jQuery 1.2, you can load JSON data from other domains by using a JSONP-style callback function, 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.

Grammar
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 The callback function executed when loading is successful.

Detailed description

This function is the abbreviation of Ajax function, which is equivalent to:

Copy code The code is as follows:

$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});

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 the 4 latest cat pictures from the Flickr JSONP API:

HTML code:

Copy code The code is as follows:


jQuery code:

Copy 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, append parameters, and display a name field data in the JSON data:

Copy code The code is as follows:

$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
alert("JSON Data: " json.users[3].name);
});
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template