xhr的属性和方法 const xhr = new XmlHttprequest()

127 阅读1分钟

image.png

完整代码如下

所有的属性和方法都在代码里

<!-- 测试接口http://suggest.taobao.com/sug?code=utf-8&q=卫衣&callback=hello -->
<script>
  const url = "https://api.vvhan.com/api/douban";
 const xhr = new XMLHttpRequest();
  // 发送之后触发xhr.onreadystatechange事件
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) {
      return;
    }
    // 结合status状态码来判断
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
      console.log("请求响应数据成功");
      // console.log(xhr.responseText);
      //   responseText是文本形式的响应内容
      //  用JSON.parse()转成json格式的对象
        const objString = JSON.parse(xhr.responseText);
      //   现在打印出来的就是一个对象
        console.log(objString);
    }
  };

  xhr.open("get", url, true);
//   timeout是设置超时时间,如果10ms之内还不能返回请求,就不返回了
//   xhr.timeout = 10;
// 跨域ajax发送请求时,是不带cookie的,如果需要携带,需要设置withCredenttials
// xhr.withCredentials = true

xhr.send();
// xhr.abort()意思是阻止请求,顺序不能写反,要写在xhr.send()的下面
// xhr.abort()
  // setRequestHeader() 方法
  // 请求头中的 Content-Type 字段用来告诉服务器,浏览器发送的数据是什么格式的
 
</script>