JSONP
For security reasons, XHRs to other domains are blocked by the browser. However, certain third-party APIs provide a response formatted as JSONP — "JSON with Padding" — which allows you to use their data even though it is hosted on another server.
JSONP isn't exactly AJAX — rather than using the browser's XHR functionality, it actually works by inserting a script tag into the page that contains the requested data, "padded" with a function wrapper. Nevertheless, jQuery lets you make a JSONP request with $.ajax() by specifying 'jsonp' as the dataType in the configuration object.
$.ajax({
url: '/data/search.jsonp',
data: { q: 'a' },
dataType: 'jsonp',
success: function( resp ) {
$( '#target' ).html( 'Results: ' + resp.results.length );
}
});
Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell YQL what we want and that we want JSON
data: {
q: "select title,abstract,url from search.news where query=\"cat\"",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
JQuery handles all the complex aspect of JSONP behind-the-scenes -- all we have to do is tell JQuery the name of the JSONP callback parameter specified by YQL, and otherwise the whole process looks and feels like a normal AJAX request.
You can also use the $.getJSON() convenience method to make a JSONP request; if the URL includes callback=? or similar, then jQuery will treat it as a JSONP request.
$.getJSON( '/data/search.jsonp?q=a&callback=?',
function( resp ) {
$( '#target' ).html( 'Results: ' + resp.results.length );
}
);