Say you had some URL that gave you JSON data like:
{'field': 'value'}
...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback
). Then it would return:
myCallback({'field':'value'})
...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction
and execute this script, it will be called with the data from the URL.
The cool thing about this is: you can create a script tag and use your URL (complete with callback
parameter) as the src
attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).
This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType
property). E.g.
$.ajax({
url: 'http://example.com/datasource',
dataType: 'jsonp',
success: function(data) {
// your code to handle data here
}
});
Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.