This question already has an answer here:
- What is JSONP all about? 8 answers
I know JSONP
is JSON
with padding.
I understand what JSON is, and how to use it with jQuery.getJSON()
. However, I do not understand the concept of the callback
when introducing JSONP.
Can anyone explain to me how this works?
Say you had some URL that gave you JSON data like:
...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g.
http://example.com/dataSource?callback=myCallback
). Then it would return:...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called
myFunction
and execute this script, it will be called with the data from the URL.The cool thing about this is: you can create a script tag and use your URL (complete with
callback
parameter) as thesrc
attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).This is what jQuery does when you make an ajax request (using
.ajax
with 'jsonp' as the value for thedataType
property). E.g.Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.
JSONP is a way of getting around the browser's same-origin policy. How? Like this:
The goal here is to make a request to
otherdomain.com
andalert
the name in the response. Normally we'd make an AJAX request:However, since the request is going out to a different domain, it won't work.
We can make the request using a
<script>
tag though. Both<script src="otherdomain.com"></script>
and$.get('otherdomain.com')
will result in the same request being made:Q: But if we use the
<script>
tag, how could we access the response? We need to access it if we want toalert
it.A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.
Q: But what if the server won't do this for us, and is only willing to return JSON to us?
A: Then we won't be able to use it. JSONP requires the server to cooperate.
Q: Having to use a
<script>
tag is ugly.A: Libraries like jQuery make it nicer. Ex:
It works by dynamically creating the
<script>
tag DOM element.Q:
<script>
tags only make GET requests - what if we want to make a POST request?A: Then JSONP won't work for us.
Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!
A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.
Preface:
This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)
JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the
XMLHTTPRequest
and the associated browser methods. Instead a<script>
tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the<head>
element).JSON Request:
JSONP Request:
The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.
JSON:
JSONP:
This is why you see JSONP requests containing the
callback
parameter, so that the server knows the name of the function to wrap the response.This function must exist in the global scope at the time the
<script>
tag is evaluated by the browser (once the request has completed).Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.
Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.
The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.
By default jQuery requires you to include
&callback=?
in the URL of your AJAX request. jQuery will take thesuccess
function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark?
in&callback=?
with the name it has assigned.Comparable JSON/JSONP Implementations
The following assumes a response object
{ "bar" : "baz" }
JSON:
JSONP:
I have found a useful article that also explains the topic quite clearly and easy language. Link is JSONP
Some of the worth noting points are:
Working is as follows:
<script src="url?callback=function_name">
is included in the html code