Jsonp
https://www.sitepoint.com/jsonp-examples/
// JavaScript - JSONP
If we need to fetch data from another server, we run into issue with the
cross origin policy. With JSONP, we overcome this issue. For JSONP to work, a
server must reply with a response that includes the JSONP function. The JSONP
function invocation that gets sent back, and the payload that the function
receives, must be agreed-upon by the client and server.
By convention, the server providing the JSON data offers the requesting website
to name the JSONP function, typically using the name jsonp or callback as the
named query parameter field name, in its request to the server, e.g.,
<script type="application/javascript"
src="http://server.example.com/Users/1234?callback=parseResponse">
</script>
In this example, the received payload would be:
parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
JSONP makes sense only when used with a script element. For each new JSONP
request, the browser must add a new <script> element, or reuse an existing one.
The former option—adding a new script element—is done via dynamic DOM
manipulation, and is known as script element injection. The <script> element
is injected into the HTML DOM, with the URL of the desired JSONP endpoint set
as the "src" attribute.
An example of using jQuery to dynamically inject script element for a JSONP
call looks like this:
$.getScript("http://server.example.com/Users/1234?callback=parseResponse");
After the element is injected, the browser evaluates the element, and performs
an HTTP GET on the src URL, retrieving the content. Then the browser evaluates
the return payload as JavaScript. This is typically a function invocation.
function logResults(json){
console.log(json);
}
$.ajax({
url: "https://api.github.com/users/jeresig",
dataType: "jsonp",
jsonpCallback: "logResults"
});
$.getJSON("https://api.github.com/users/jeresig?callback=?",function(json){
console.log(json);
});
The ? on the end of the URL tells jQuery that it’s dealing with a JSONP request
instead of JSON. jQuery then automatically registers the callback function which
it calls when the request retruns.
There are some drawbacks with JSONP. JSONP can only perform cross-domain GET
requests and the server must explicitly support it. There are also security
concern when the other server is hacked.
I think JSONP works by dynamically inserting script tags.
page revision: 3, last edited: 14 Nov 2016 20:36





