[Vue.js] 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 and Vue.js.

{{ info }}

Source Code and Explanation

HTML:

<div id="vueapp">
  <button v-on:click.once="jsonp">Click to get HTTP header via JSONP</button>
  <pre>{{ info }}</pre>
</div>

<script src="https://unpkg.com/vue@2.2.4/dist/vue.js"></script>

Register an click event handler of the button element, and run the click event handler only once.

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 vm = new Vue({
  el: '#vueapp',
  data: {
    info: ""
  },
  methods: {
    jsonp: function() {
      this.info = "Loading ...";
      var tag = document.createElement("script");
      tag.src = "https://ajaxhttpheaders.appspot.com/?callback=myCallback";
      document.querySelector("head").appendChild(tag);
    }
  }
})

function myCallback(acptlang) {
  vm.info = acptlang;
}

The name of the callback function in demo is myCallback. In the click event handler, 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)
  • Vue.js 2.2.4

References:

[1]
[2]JSONP on Google App Engine Python
[3]Event Handling — Vue.js