11

[Vue.js] AJAX XMLHttpRequest (XHR) Example

 3 years ago
source link: http://siongui.github.io/2017/03/22/vuejs-ajax-xmlhttprequest-xhr-example/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Vue.js] AJAX XMLHttpRequest (XHR) Example

March 22, 2017

Example for XMLHttpRequest (XHR) by Vue.js, which helps you transfer data between a client and a server. This is usually used to retrieve data from a URL, and update only part of the webpage without full refresh.

The following demo make HTTP GET XHR request to the given URL.

This demo can also make cross-domain requests if the server supports CORS, which has the Access-Control-Allow-Origin header set properly. You can try the following cross-domain URL in the demo:

https://golden-operator-130720.appspot.com/sukhada.json

Source Code and Explanation

HTML:

<div id="vueapp">
  URL: <input type="text" v-model.trim="url" v-on:keyup.enter="xhr">
  <button v-on:click="xhr">XHR</button><br>
  <pre>{{ info }}</pre>
</div>

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

If the user press the button or enter key in the input element, use the value of the input element as URL and make HTTP GET request by xhr method.

JavaScript:

'use strict';

new Vue({
  el: '#vueapp',
  data: {
    url: "https://siongui.github.io/xemaauj9k5qn34x88m4h/sukhada.json",
    info: ""
  },
  methods: {
    xhr: function() {
      this.info = "Requesting ...";
      var rq = new XMLHttpRequest();

      rq.onreadystatechange = function(vm) {
        if (this.readyState === XMLHttpRequest.DONE) {
          if (this.status === 200) {
            vm.info = this.responseText;
          } else {
            vm.info = "Request Failed";
          }
        }
      }.bind(rq, this);

      rq.open("GET", this.url);
      rq.send();
    }
  }
})

The implementation of xhr method is the same as the code in other tutorials, except that we use bind method to assign the value of this and pass the Vue instance to the onreadystatechange event handler.

If you web page is served via HTTPS, the server that returns data 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:


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK