English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSONP Tutorial

Jsonp (JSON with Padding) is a 'usage pattern' of json, which allows web pages to obtain data from other domains (websites), that is, to read data across domains.

What is JSONP?

JSONP stands for JSON with Padding.

Requesting a file from another domain may cause problems due to cross-domain policies.

Requesting an external script from another domain does not have this problem.

JSONP takes advantage of this and uses<script>using a tag instead of an XMLHttpRequest object to request the file.

  <script src="jsonp_demo.php">

The file on the server (jsonp_demo.php) wraps the result in a function call:

  <?php
  $myJSON = '{ "name":"Seagull", "age":32, "city":"New Delhi" }';
  echo "myFunc(".$myJSON.");";
  ?>

The function named 'myFunc' is located on the client side and can handle JSON data:

function myFunc(myObj) {
  document.getElementById("output").innerHTML = myObj.name;
}
Test and see‹/›

Difference Between JSON and JSONP

JSON: JavaScript uses JSON (JavaScript Object Notation) to exchange data over the network. It carefully examines the JSON data, which is simply a string-formatted JavaScript object.

JSON Example:
  { "name":"Seagull", "age":22, "city":"New Delhi" }

JSONP: JSONP is filled JSON. Here, filled means wrapping the function in JSON and then returning it in the request.

JSONP Example:
  myFunc({ "name":"Seagull", "age":22, "city":"New Delhi" })

Methods of Using JSONP

  • In HTML code, include the script tag. The source of the script tag will be the URL from which data is to be retrieved. Web services allow specifying a callback function. The last part of the URL contains the callback parameter.

  • When the browser encounters a script element, it sends an HTTP request to the source URL.

  • The server sends back the response using JSON enclosed in a function call.

  • The browser parses the JSON response in string format and converts it to a JavaScript object. It calls the callback function and passes the generated object to it.

Create Dynamic Script Tag

The example above will execute the "myFunc" function at the position where the script tag is placed when the page is loaded.

However, script tags should only be created when necessary.

The following example will create and insert<script>Label:

function createScriptDynamically() {
  var elem = document.createElement("script");
  elem.src = "jsonp_demo.php";
  document.body.appendChild(elem);
}
Test and see‹/›