发送http请求

发送http请求

XHR

特点:向服务器请求数据而不刷新页面

xhr发送get请求
      const dom = document.querySelector(".xhrGet");
      dom.addEventListener("click", xhrGet);

      function xhrGet() {
        const xhr = new XMLHttpRequest();  // 创建一个XHR对象
        xhr.onreadystatechange = function () {  // 监听xhr对象的readyState
          if (xhr.readyState == 4) {   
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
              console.log(xhr.responseText);
            } else {
              console.log("request fail");
            }
          }
        };
        // 请求方法及地址,可选参数布尔值--表示是否异步
        xhr.open("get", "http://localhost:8080/api/contactList");
        xhr.send(null);   // 请求体的数据,没有则为null
      }
xhr发送post请求
      const btn = document.querySelector(".xhrPost");
      btn.addEventListener("click", xhrPost, false);
      function xhrPost() {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
              console.log(xhr.responseText);
            } else {
              console.log("request fail");
            }
          }
        };
        xhr.open("post", "http://localhost:8080/api/contact/new/json");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(
          JSON.stringify({
            name: "钢弹",
            tel: 15025455666,
          })
        );
      }
xhr的方法
// 终止当前请求
xhr.abort()
// 设置请求头信息
xhr.setRequestHeader("Content-Type","application/json")
xhr事件**

timeout事件

如果发送请求后8秒,响应不成功,那么请求会中断,触发timeout的事件处理程序;readystate会变为4;仍然会调用onreadystatechagne事件处理程序,但是此时访问status会报错,所以最好把status放在try/catch中

        xhr.timeout = 8000;
        xhr.addEventListener("timeout", function () {
          console.log("require fail,timeout");
        });

error事件

请求发生错误时触发

        xhr.addEventListener("error", function () {
          console.log("require error");
        });

abort事件

当请求中断时调用事件处理程序,比如请求超时,或者自己调用abort方法

        xhr.addEventListener("abort", function () {
          console.log("require aborted");
        });

readystatechange事件

前面例子中使用过了

readyState的值及含义

0:尚未初始化,未调用open

1: 已调用open,但没调用send

2: 已发送(已经调用send),未收到响应

3: 接受中,已接到vu分响应

4: 响应接收完成

load事件

作用和readystatechagne事件一样,相当于是它的一个替代品,ie9开始支持

        xhr.addEventListener("load", function () {
          console.log("get response");
        });

Fetch

特点:基于Promise设计,更加语义化,好理解

fetch发送get请求
      const fetchGetBtn = document.querySelector(".fetchGet");
      fetchGetBtn.addEventListener("click", fetchGet);
      function fetchGet() {
        fetch("http://localhost:8080/api/contactList").then((res) => {
          res.text().then((data) => {
            console.log(data);
          });
        });
      }
fetch发送post请求
      const fetchPostBtm = document.querySelector(".fetchPost");
      fetchPostBtm.addEventListener("click", fetchPost);
      function fetchPost() {
        fetch("http://localhost:8080/api/contact/new/json", {
          method: "POST",
          body: JSON.stringify({ name: "ghost", tel: 11044444444 }),
          headers: new Headers({ "Content-Type": "application/json" }),
        }).then((res) => {
          res.text().then((data) => console.log(data));
        });
      }

fetch相比于xhr

优点:基于promise,支持async/await; fetch的语法简洁,更语义化

缺点:

  1. fetch只对网络错误报错,http状态码错误不报错
  2. fetch不支持abort,无法终止
  3. fetch不支持超时控制,使用setTimeout和Promise.reject实现的超时控制不能阻止请求过程继续在后台运行,造成了流量的浪费
  4. fetch没有原生检测请求进度的方式,XHR可以
  5. 默认情况下fetch不发送cookie,除非手动配置
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值