ドキュメント

Ajax/jQuery.getJSON

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Ajax

jQuery.getJSON( url, [data][callback] )

Load JSON data using an HTTP GET request.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback.

The callback takes the form "example.com?callback=?". jQuery automatically replaces the '?' with a random method name that doesn't clash with the global scope. You do not have to specify the method name yourself.

Note that the site you're trying to call needs to support JSON-P output. The callback parameter might vary depending on the API, for instance Yahoo Pipes requires "_callback=?"

Keep in mind, that lines after this function will be executed before the callback.
Arguments:

urlString
The URL of the page to load.
data (Optional)Map
Key/value pairs that will be sent to the server.
callback (Optional)Function
A function to be executed whenever the data is loaded successfully.
function (data, textStatus) {
  // data will be a jsonObj
  // textStatus will be "success"
  this; // the options for this ajax request
}
Examples:

Loads the four most recent cat pictures from the Flickr JSONP API.

$.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;
          });
        });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $.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;
          });
        });
  });
  </script>
  <style>img{ height: 100px; float: left; }</style>
</head>
<body>
  <div id="images">
  </div>
</body>
</html>

Load the JSON data from test.js and access a name from the returned JSON data.

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

Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.

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

List the result of a consultation of pages.php in HTML as an array. By Manuel Gonzalez.

var id=$("#id").attr("value");
  $.getJSON("pages.php",{id:id},dates);
function dates(datos)
{
	
 $("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address);
}

NameType