I have a two domains, example1.com and example2.com
From example1.com, I would like call a JSON API I have on example2.com. Knowing that this is not allowed, it occurred to me - this is exactly why JSONP was created.
Question is, how do I modify my JSON API to make it JSONP capable?
Basically, how do I create the callback api?
UPDATE
My server side language is PHP
Mauris already gave you a working example. I would only add that you should check if a
callback
param is present and non-empty, and if not, return the json data as is without the parentheses. So basically your api will be JSON with provision of being JSON-P whencallback
is given.To consume the JSON-P webservice, unless you use a framework like YUI or jQuery, you can simply create a script node dynamically and set its
src
attribute to point to the webservice. Remember to remove the node from the dom before repeating it again, since this dynamic script node is single use only.example here http://www.insideria.com/2009/03/what-in-the-heck-is-jsonp-and.html basically
It is simple. Simply accept a parameter called
callback
in the GET.Then wrap the callback JavaScript function around your data.
Example in PHP:
It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function.
You can use the built-in
json_encode()
function to create JSON strings (which$data
in our example above contains) from arrays and objects in PHP.To use the JSONP service, you can use the
<script>
tag:I know I'm late to the party, and there was a comment about security of the code in one of the answers. Here is a good article about this:
http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
And here is the code that you should be running:
You can use the Simple JSON for PHP to forge it! It simplify everything!
You need a server-side language, the callback parameter is simply a GET parameter, you read the param, and you wrap the JSON response into a function call and you print it like this
callback(jsonResponse);
.I leave you a really minimalist example using Python since you don't mention any server-side language:
That is the code of a small JSONP service used to retrieve the client IP address made by Zach and it is hosted on the Google App Engine.