// 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"

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:
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){
  url: "https://api.github.com/users/jeresig",
  dataType: "jsonp",
  jsonpCallback: "logResults"


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.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License