The way to use XMLHttpRequest (XHR) in Vue to get data is the same as traditional HTML pages. The following is the detailed usage of XMLHttpRequest in Vue:
- Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
- Set request parameters
xhr.open('GET/POST', url, true); //第三个参数是是否异步请求,默认为true
- Listen for state changes
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//请求成功
}
}
- send request
xhr.send(data); //data是请求参数,可以是字符串、FormData等
- Get response data
//String类型,返回的响应数据,如果响应内容类型是json,则需要解析
xhr.responseText
//XMLDocument类型,返回XML格式的响应数据
xhr.responseXML
In Vue, you can encapsulate XHR in methods in methods, and then call this method in the Vue instance to achieve data acquisition and rendering. Here is a simple example:
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id">{
{item.title}}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: []
}
},
methods: {
getList() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
this.list = JSON.parse(xhr.responseText);
}
}.bind(this);
xhr.send();
}
},
mounted() {
this.getList();
}
}
</script>
What about XMLHttpRequest?
The bottom layer of XMLHttpRequest (XHR) is implemented based on the HTTP protocol.
The XMLHttpRequest object has a readyState attribute, indicating the state of the XMLHttpRequest object.
- When readyState is 0, the XMLHttpRequest object has been created but not yet initialized.
- When readyState is 1, the XMLHttpRequest object has called the open() method, but the request has not been sent yet.
- When readyState is 2, the XMLHttpRequest object has sent the request, but has not received the response.
- When the readyState is 3, the XMLHttpRequest object has received part of the response data.
- When the readyState is 4, the XMLHttpRequest object has received all response data and parsed it.
The XMLHttpRequest object also has a status attribute, which indicates the HTTP response status code. Common HTTP status codes include 200 indicating a successful request, 404 indicating that the requested resource was not found, and 500 indicating an internal server-side error.
When the XMLHttpRequest object receives an HTTP response, the client script will determine the type of the response content according to the Content-Type field in the response header.
- If the Content-Type is text/xml, the client script can use the responseXML attribute to get the response data in XML format.
- If the Content-Type is text/plain or application/json, the client script can use the responseText property to get the response data in plain text format, and then parse it into a JSON object.