JavaScript: How do I create JSONP? JavaScript: How do I create JSONP? json json

JavaScript: How do I create JSONP?


It is simple. Simply accept a parameter called callback in the GET.

Then wrap the callback JavaScript function around your data.

Example in PHP:

<?php$data = '{}'; // json stringif(array_key_exists('callback', $_GET)){    header('Content-Type: text/javascript; charset=utf8');    header('Access-Control-Allow-Origin: http://www.example.com/');    header('Access-Control-Max-Age: 3628800');    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');    $callback = $_GET['callback'];    echo $callback.'('.$data.');';}else{    // normal JSON string    header('Content-Type: application/json; charset=utf8');    echo $data;}

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:

<script>    function receiver(data){        console.log(data);    }</script><script src="data-service.php?callback=receiver"></script>


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:

import osimport cgiform = cgi.FieldStorage()callback = form.getvalue('callback','')address = cgi.escape(os.environ["REMOTE_ADDR"])json = '{"ip": "'+address+'", "address":"'+address+'"}'#Allow cross domain XHRprint 'Access-Control-Allow-Origin: *'print 'Access-Control-Allow-Methods: GET'if callback != '':  print 'Content-Type: application/javascript'  result = callback+'('+json+');'else:  print 'Content-Type: application/json'  result = jsonprint ''print result

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.


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 when callback 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.