The same origin policy is a security policy that all the modern browsers apply to client-side scripting languages, including JavaScript. That policy prevents a script running in the browser from calling methods and resources offered by different websites from the one that hosts the script
For example if a script, hosted on www.site-a.com, tries to make an AJAX request (using XmlHttpRequest) to www.site-b.com, the request is blocked:
Sometimes you need to bypass this restriction: for example think about a website that – using JavaScript – has to retrieve tweets from Twitter… the solution is called JSONP!
JSONP
JSONP (JSON with padding) is a communication technique that extends JSON data-exchange format.
This technique take advantage of the lazy loading, that is the ability to add – at runtime – new scripts to an HTML page. This method is not restricted by the same origin policy.
A normal JSON response contains data, for example:
{ title: “La Divina Commedia”, author: “Dante Alighieri” } |
With JSONP instead, data is passed as argument of a callback function:
buyBook({ title: “La Divina Commedia”, author: “Dante Alighieri” }); |
The response to a JSONP request is therefore a JavaScript code, that is run by the browser.
Dynamic callback
In the previous example, the callback funcion’s name is static; with a change in the server-side method that creates the JSONP response, you can make it dynamic, able to respond to any JSONP request.
The trick is to pass, as a request’s parameter, the name of the function:
http://www.site-b.com/getData?callback=myCallBack
the server-side script will create the JSONP response using that parameter… for example in PHP:
$data = array('title' =--> 'La Divina Commedia', 'author' => 'Dante Alighieri'); $json = json_encode($data); $jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null; print $jsonp_callback ? "$jsonp_callback($json)" : $json; |
jQuery
jQuery makes easy the use of JSONP: you need only to add callback=? to the URL in the getJSON method and jQuery will generate a callback function for you:
If the URL includes the string “callback=?” (or similar, as defined by the server-side API), the request is treated as JSONP instead
With the more general ajax method you can instead change all the request’s settings, including the name of the function.
É sempre piacevole cercare un argomento sul web e scoprire che tu lo hai già trattato in maniera ineccepibile e chiara 🙂
Grande Luca