[JavaScript] JSONP Example


Demo

JSONP is a method which help you retrieve data from other domains. The following demo will show the headers of your HTTP request via JSONP.


Source Code and Explanation

HTML:

<button id="btn">Click to get HTTP header via JSONP</button>
<pre id="result"></pre>

JavaScript:

Someone provide online service which returns HTTP request headers via JSONP. The URL of the service is:

https://ajaxhttpheaders.appspot.com/?callback={{YOUR_CALLBACK_NAME}}

If you want to know how to implement the server which returns data via JSONP, see [1]. The front-end JavaScript code for retrieving HTTP request headers from the above service via JSONP is as follows:

'use strict';

var btn = document.getElementById("btn");
var result = document.getElementById("result");

function myCallback(acptlang) {
  result.innerHTML = JSON.stringify(acptlang, null, 2);
}

function jsonp() {
  result.innerHTML = "Loading ...";
  var tag = document.createElement("script");
  tag.src = "https://ajaxhttpheaders.appspot.com/?callback=myCallback";
  document.querySelector("head").appendChild(tag);
}

btn.addEventListener("click", jsonp);

You need to assign a callback function, which receives data from the server, in the JSONP request. The name of the callback function in the demo is myCallback. In the click event handler, the JSONP action is performed. A script element is created and then appended to the end of head element. The source of the script element is the URL of the online service, and the name of the callback is assigned in the query string of the URL.

Note

If you web page is served via HTTPS, the server that returns data via JSONP also needs to serve via HTTPS. Otherwise browsers will block the request and make the request fail.


Tested on:

  • Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]
[2][Vue.js] Pretty Print JSON String