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

Example of getJSON() usage in jQuery+ajax

高洛峰
Release: 2017-01-12 10:04:09
Original
1097 people have browsed it

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);
});
Copy after login

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
});
Copy after login

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>
Copy after login

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;
  });
});
Copy after login

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);
});
Copy after login

More jQuery +Please pay attention to the PHP Chinese website for related articles on getJSON() usage examples in ajax!

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