Does JSONP require server modifications?
Asked Answered
K

1

32

I understand that jsonp is a technique to get around the same origin policy. You basically refer to your json serving server endpoint in a script tag, because script tags are exempt from the SO policy.

My question is: Assuming a server has an endpoint that serves up json, are there any modifications necessary on the server to make use of jsonp in the client?

I think no, but want to be sure....

Kippar answered 21/7, 2010 at 1:33 Comment(0)
C
37

Yes, JSONP is slightly different when it renders, so your server needs to support it.

JSON looks like this:

{ "name": "value" }

Whereas JSONP looks like this:

functionName({ "name": "value" });

If whatever you're using supports it you're covered, but it's not the same as supporting just JSON. When the server gets a request, for example: http://example.com/json?callback=functionName, the above is what you should render, because how it looks in the page is this:

<script type="text/javascript" src="http://example.com/json?callback=functionName"></script>

This means something that runs needs to be returned, as an illustration, this is valid:

<script type="text/javascript">
  functionName({ "name": "value" });
</script>

If your server didn't support JSONP it would effectively be this:

<script type="text/javascript">
  { "name": "value" }
</script>

...and you'll get syntax errors, since that's not valid JavaScript.

Cicely answered 21/7, 2010 at 1:35 Comment(5)
and your js code has to implement functionName? Does it need to eval the json to get the js objects?Kippar
@Kippar - Yes, the client has that function (for example jQuery creates one dynamically by default). It's JSON being passed to the function (JSON is valid object literal notation, just a subset of it), so no eval() needs to be done.Cicely
i don't understand why you don't need to eval it. Regardless of jsonp, dont most js libraries eval the json returned via xhrs to get the actual js objects the json represents?Kippar
@Kippar - Nope, it's not running through JavaScript (or XmlHttpRequest), it's literally a <script> element added to the page...it's fetched like any other .js file. It's a normal GET...that's why it's allowed cross-domain where normal AJAX requests aren't. In the case of JSON the response is either eval'd or better, uses the native JSON.parse() several browsers have implemented....but JSONP is a different ballgame.Cicely
My understanding is that the decision about how to process any script tag content (i.e. whether to parse it at native code level or to offer it to a high-level JavaScript eval function) is left to the implementor of the browser.Mete

© 2022 - 2024 — McMap. All rights reserved.