[Vue.js] AJAX XMLHttpRequest (XHR) Example
Demo
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.
{{ info }}
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/vue@2.2.4/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.
Note
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:
[1] |