Possible Duplicate:
Ajax cross domain call
My application is using ASP .Net Web API 4.5 RTM that interacts with HTML5 and AJAX on a different domain.
Does this application needed to use JSONP instead of JSON for serialization/deserialization?
JSONP or JSON with padding
is a complement to the base JSON data format. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.
Under the same origin policy, 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 element. Exploiting the open policy for elements, some pages use them to retrieve JavaScript code that operates on dynamically generated JSON-formatted data from other origins. This usage pattern is known as JSONP.
Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.
To see how this pattern works, first consider a URL request that returns JSON data. A JavaScript program might request this URL via XMLHttpRequest
, for example. Suppose the UserId of Foo is 1234. A browser requesting the URLhttp://server2.example.com/Users/1234, passing the Id of Foo, would receive something like:
{"Name": "Foo", "Id": 1234, "Rank": 7}
This JSON data could be dynamically generated, according to the query parameters passed in the URL. Here, an HTML element specifies for its src attribute a URL that returns JSON:
<script type="text/javascript"
src="http://server2.example.com/Users/1234">
</script>
The browser will, in order, download the script file, evaluate its contents, interpret the raw JSON data as a block, and throw a syntax error. Even if the data was interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment object literals are inaccessible.
In the JSONP usage pattern, the URL request pointed to by the 's src attribute returns JSON data, with a function call wrapped around it. In this way, a function that's already defined in the JavaScript environment can manipulate the JSON data. A JSONP payload might look like this:
functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});
The function call is the "P" of JSONP - the "padding" around the pure JSON, or according to some[1] the "prefix". By convention, the browser provides the name of the callback function as a named query parameter, typically using the name JSONP or callback, in its request to the server, e.g.,
<script type="text/javascript"
src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>
In this example, the received payload would be:
parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With