1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
|
<!DOCTYPE html>
<html lang='en'><head><meta http-equiv='content-type' content='text/html; charset=UTF-8' /></head><body>
<div class="entry-content">
<div class="entry-title roundTop">
<h1 class="jq-clearfix">jQuery.getJSON()</h1>
<div class="entry-meta jq-clearfix">
Categories:
<span class="category"><a href="http://api.jquery.com/category/ajax/" title="View all posts in Ajax">Ajax</a> > <a href="http://api.jquery.com/category/ajax/shorthand-methods/" title="View all posts in Shorthand Methods">Shorthand Methods</a></span>
</div>
</div>
<div id="jQuery-getJSON1" class="entry method">
<h2 class="jq-clearfix roundTop section-title">
<span class="name">jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )</span> <span class="returns">Returns: <a class="return" href="http://api.jquery.com/Types/#jqXHR">jqXHR</a></span>
</h2>
<div class="jq-box roundBottom entry-details">
<p class="desc"><strong>Description: </strong>Load JSON-encoded data from the server using a GET HTTP request.</p>
<ul class="signatures"><li class="signature" id="jQuery-getJSON-url-data-successdata- textStatus- jqXHR">
<h4 class="name">
<span class="versionAdded">version added: <a href="/category/version/1.0/">1.0</a></span>jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )</h4>
<p class="arguement"><strong>url</strong>A string containing the URL to which the request is sent.</p>
<p class="arguement"><strong>data</strong>A map or string that is sent to the server with the request.</p>
<p class="arguement"><strong>success(data, textStatus, jqXHR)</strong>A callback function that is executed if the request succeeds.</p>
</li></ul>
<div class="longdesc">
<p>This is a shorthand Ajax function, which is equivalent to:</p>
<pre>$.ajax({
url: <em>url</em>,
dataType: 'json',
data: <em>data</em>,
success: <em>callback</em>
});
</pre>
<p>Data that is sent to the server is appended to the URL as a query string. If the value of the <code>data</code> parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.</p>
<p>Most implementations will specify a success handler:</p>
<pre>$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</pre>
<p>This example, of course, relies on the structure of the JSON file:</p>
<pre>{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
</pre>
<p>Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.</p>
<p>The <code>success</code> callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the <code><a href="/jQuery.parseJSON">$.parseJSON()</a></code> method. It is also passed the text status of the response.</p>
<p><strong>As of jQuery 1.5</strong>, the <code>success</code> callback function receives a <a href="http://api.jquery.com/jQuery.get/#jqxhr-object">"jqXHR" object</a> (in <strong>jQuery 1.4</strong>, it received the <code>XMLHttpRequest</code> object). However, since JSONP and cross-domain GET requests do not use <abbr title="XMLHTTPRequest">XHR</abbr>, in those cases the <code>jqXHR</code> and <code>textStatus</code> parameters passed to the success callback are undefined.</p>
<blockquote>
<p><strong>Important:</strong> As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see <a href="http://json.org/">http://json.org/</a>.</p>
</blockquote>
<h4 id="jsonp">JSONP</h4>
<p>If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the <code>jsonp</code> data type in <code><a href="http://api.jquery.com/jQuery.ajax/">$.ajax()</a></code> for more details.</p>
<h4 id="jqxhr-object">The jqXHR Object</h4>
<p><strong>As of jQuery 1.5</strong>, all of jQuery's Ajax methods return a superset of the <code>XMLHTTPRequest</code> object. This jQuery XHR object, or "jqXHR," returned by <code>$.getJSON()</code> implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see <a href="http://api.jquery.com/category/deferred-object/">Deferred object</a> for more information). For convenience and consistency with the callback names used by <code><a href="http://api.jquery.com/jQuery.ajax/">$.ajax()</a></code>, it provides <code>.error()</code>, <code>.success()</code>, and <code>.complete()</code> methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named <code>$.ajax()</code> callback.</p>
<p>The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including <code>$.getJSON()</code>, to chain multiple <code>.success()</code>, <code>.complete()</code>, and <code>.error()</code> callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.</p>
<pre>// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });</pre>
</div>
<h3 id="notes-0">Additional Notes:</h3>
<div class="longdesc"><ul>
<li>Due to browser security restrictions, most "Ajax" requests are subject to the <a title="Same Origin Policy on Wikipedia" href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin policy</a>; the request can not successfully retrieve data from a different domain, subdomain, or protocol.</li>
<li>Script and JSONP requests are not subject to the same origin policy restrictions.</li>
</ul></div>
<h3>Examples:</h3>
<div class="entry-examples" id="entry-examples">
<div id="example-0">
<h4>Example: <span class="desc">Loads the four most recent cat pictures from the Flickr JSONP API.</span>
</h4>
<pre class="prettyprint"><code class="example demo-code"><!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-1.7rc2.js"></script>
</head>
<body>
<div id="images">
</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});</script>
</body>
</html></code></pre>
<h4>Demo:</h4>
<div class="demo code-demo"></div>
</div>
<div id="example-1">
<h4>Example: <span class="desc">Load the JSON data from test.js and access a name from the returned JSON data.</span>
</h4>
<pre class="prettyprint"><code class="example">$.getJSON("test.js", function(json) {
alert("JSON Data: " + json.users[3].name);
});</code></pre>
</div>
<div id="example-2">
<h4>Example: <span class="desc">Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.</span>
</h4>
<pre class="prettyprint"><code class="example">$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});</code></pre>
</div>
</div>
</div>
</div>
</div>
</body></html>
|