Vue中XMLHttpRequest的详细使用方法

Vue中使用XMLHttpRequest(XHR)来获取数据的方式与传统的HTML页面相同。以下是Vue中XMLHttpRequest的详细使用方法:

  1. 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
  1. 设置请求参数
xhr.open('GET/POST', url, true); //第三个参数是是否异步请求,默认为true
  1. 监听状态变化
xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    
    
        //请求成功
    }
}
  1. 发送请求
xhr.send(data); //data是请求参数,可以是字符串、FormData等
  1. 获取响应数据
//String类型,返回的响应数据,如果响应内容类型是json,则需要解析
xhr.responseText
 //XMLDocument类型,返回XML格式的响应数据
xhr.responseXML

在Vue中,可以将XHR封装在methods中的方法里,然后在Vue实例中调用该方法来实现数据的获取和渲染。以下是一个简单的例子:

<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>
  

XMLHttpRequest 是怎么回事 ?

XMLHttpRequest(XHR)底层是基于HTTP协议实现的。
XMLHttpRequest对象有一个readyState属性,表示XMLHttpRequest对象的状态。

  • 当readyState为0时,XMLHttpRequest对象已经创建,但还未初始化。
  • 当readyState为1时,XMLHttpRequest对象已经调用open()方法,但还未发送请求。
  • 当readyState为2时,XMLHttpRequest对象已经发送请求,但还未接收到响应。
  • 当readyState为3时,XMLHttpRequest对象已经接收到部分响应数据。
  • 当readyState为4时,XMLHttpRequest对象已经接收到全部响应数据并解析完毕。

XMLHttpRequest对象还有一个status属性,表示HTTP响应状态码。常见的HTTP状态码有200表示请求成功,404表示请求的资源未找到,500表示服务器端内部错误等。

当XMLHttpRequest对象接收到HTTP响应时,客户端脚本会根据响应头中的Content-Type字段来判断响应内容的类型。

  • 如果Content-Type为text/xml,客户端脚本可以使用responseXML属性来获取XML格式的响应数据。
  • 如果Content-Type为text/plain或application/json,客户端脚本可以使用responseText属性来获取纯文本格式的响应数据,然后解析成JSON对象。

猜你喜欢

转载自blog.csdn.net/zl18603543572/article/details/130589556
今日推荐