JSONP
Encyclopedia
JSONP or "JSON with padding" is a complement to the base JavaScript Object Notation JSON
JSON
JSON , or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects...

 data format, a pattern of usage allowing a page to request data from a server in a different domain. JSONP is a solution to this problem, forming an alternative to a more recent method named Cross-Origin Resource Sharing
Cross-Origin Resource Sharing
Cross-Origin Resource Sharing is a web browser technology specification, which defines ways for a web server to allow its resources be accessed by a web page from a different domain...

.

Under the same origin policy
Same origin policy
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...

, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

 


In this example, the received payload would be:


parseResponse({"Name": "Foo", "Id" : 1234, "Rank": 7})

Padding

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other JavaScript statement.
The response to a JSONP request (namely, a request following the JSONP usage pattern) is not JSON and is not parsed as JSON; the returned payload can be any arbitrary JavaScript expression, and it does not need to include any JSON at all. But conventionally, it is a JavaScript fragment that invokes a function call on some JSON-formatted data.

Said differently, the typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call.

Script element injection

JSONP makes sense only when used with a script element. For each new JSONP request, the browser must add a new