JSONP is basically a "hack" to allow sites to load data and ignore the same-origin policy. It works by appending a <script>
tag to your page.
The de facto way is to send a callback in your request. The server would then take that name and generate a JS file that calls that function with the data.
Using jQuery, you can make a JSONP call by simply appending ?callback=?
to your URL when doing $.getJSON
.
Example:
$.getJSON('http://YourSite.com/path/to/json.php?callback=?', function(data){
console.log(data); // this will be parsed for you
});
Or, you can use the full $.ajax
method:
$.ajax({
url: 'http://YourSite.com/path/to/json.php',
dataType: 'jsonp', // this tells jQuery to add "callback=?" for you
success: function(data){
console.log(data); // this will be parsed for you
}
});
Instead of makning an AJAX call, jQuery will actually append:
<script src="http://YourSite.com/path/to/json.php?callback=jQuery12345"></script>
to your page (note: jQuery12345
will be randomly generated).
Then on your server, you need to respond with a valid JavaScript file. It should contain a call to the callback
function passed in the query string. Something like this:
jQuery12345({your: ['json', 'data']});
An example in PHP (adapt to whatever server-side language you use) could be:
$array = ['a' => 1, 'b' => 2,'c' => 3];
$callback = $_GET['callback'];
header('Content-type: text/javascript');
echo "{$callback}(".json_encode($array).");";
That's all there is to it. See the Wikipedia page on JSONP for more info: http://en.wikipedia.org/wiki/JSONP