JSON or JSONP
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.