lamp

JSON or JSONP

Published 15 June 08 11:19 AM | Frederick.Chapleau

What's the difference, and why should we always use JSON-P.

JSON is a simple anonymous result, without a callback method. So, you should retrieve the result, using a XMLHTTPRequest, and after that, interpret the result with the eval JavaScript function. That's nice, but, not enough, when you want to call server side functionality cross-domain.

From wikipedia, here is an example of a the result to a JSON call.

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

That's why JSON-P was created. JSON-P is the padded version that allow to provide a Callback method to the provided JavaScript. So, the result is a function call, and not an anonymous JavaScript object. With that, you can include the code, using the Script HTML tag, and bypass the same origin policy.

Here is an example of a JSON-P result.

callbackMethodProvided(eval('{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] }'"));

 

The facts

When using JSON, you can only get scripts from your own domain, because JSON can not work with the non-restrictive HTML Script tag. And with JSONP, you can get everything from everywhere.

That's why, if you expose an API to the world, just support callback (JSONP), if not, each and every developer should create a kind of proxy on their server to request JSON script and  give it to web clients...

-f.

 
Filed under:

Comments

# User links about "jsonp" on iLinkShare said on January 21, 2009 08:18 AM:

Pingback from  User links about "jsonp" on iLinkShare

# Recent Faves Tagged With "jsonp" : MyNetFaves said on May 3, 2009 10:50 AM:

Pingback from  Recent Faves Tagged With "jsonp" : MyNetFaves

# Websites tagged "jsonp" on Postsaver said on July 20, 2009 07:02 PM:

Pingback from  Websites tagged "jsonp" on Postsaver

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Protected by FormShield
Refresh
Listen
Please enter the characters shown on the image


Code: