XMLHttpRequest

312 阅读2分钟

post请求

  1. 创建xhr对象。
  2. 注册 xhr.onreadystatechange 事件,当Ajax请求成功后,会触发onload函数。在 readystatechange 函数中,接收响应结果。
  3. 调用open方法,初始化一个请求,此方法用于配置请求方式和url。
  4. 调用setRequestHeader方法,设置请求头。
  5. 调用send方法,发送请求。
   let xhr = new XMLHttpRequest();

    // 2. 准备事件,获取服务器响应结果
    xhr.onreadystatechange = function () {
      let res = xhr.responseText;
      console.log(res);
    }

    // 3. 设置请求方式和url地址
    xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook');

    // 4. 设置请求头  Content-Type用来指定请求体的类型 (查询字符串,json,formdata)
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // 5. 调用send发送请求
    let b = encodeURIComponent('红&黑');
    xhr.send('bookname=' + b + '&author=yyy&publisher=ssss');
    

readyState

我们可以把整个请求响应过程划分为5个阶段。并且可以使用 xhr.readyState 属性检测当前请求执行到哪个阶段了。

image.png

var xhr = new XMLHttpRequest();

console.log(xhr.readyState); // ===> 0  xhr刚创建

// 2. 注册 xhr.onreadystatechange 事件,当Ajax请求**成功**后,会触发onload函数。在 readystatechange 函数中,接收响应结果。
onreadystatechange  当 readyState 改变的时候,下面的 事件就会触发
xhr.onreadystatechange = function () {
  console.log(xhr.readyState); // ===> 1,2,3,4
  // 使用 xhr.response 接收响应结果
  var res = xhr.responseText;
}

// 3. 调用open方法,设置请求方式及请求的url地址
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记');

// 4. 最后,调用send方法,发送这次ajax请求
xhr.send();

使用XMLHttpRequest 封装ajax

                        对象解构赋值
  function myAjax({type,data,success,url}) {
      let xhr = new XMLHttpRequest(); 
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          let res = xhr.responseText;
          success(res);  //给success方法传实参(服务器返回结果,字符串类型)
        }
      }
      let arr = [];
      for (let key in data) {
        arr.push(`${key}=${data[key]}`);     //把对象转为数组
      }
      console.log(arr);  //  ["bookname=西游记", "author=sss", "publisher=dddd"]
      let str = arr.join('&');   //通过join把数组每一项用&拼接起来
      // str就是查询参数
      if (type === 'GET') {   // 如果是GET 就把str拼接到url后边
        xhr.open('GET', url + '?' + str);
        xhr.send();
      } else if (type === 'POST') { // 如果是POST 就把str放到 send()里
        xhr.open('POST', url);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(str);
      }
    }
    myAjax({
            type: 'POST',
            url: 'http://www.liulongbin.top:3006/api/addbook',
            data: { bookname:'西游记',author: 'sss', publisher: 'dddd'},
            success: function (str) {
                // res 表示服务器返回的结果
                console.log(str);
            }
        });

同步ajax

同步的Ajax请求了解即可,因为它会阻塞代码的运行,开发中基本不用。

jquery:

 $.ajax({
    url: 'http://www.liulongbin.top:3006/api/getbooks',
    success: function (res) {
        console.log(222)
    },
    async: false // 默认true,
    如果改为false,表示发送 同步 的Ajax请求
});

原生代码,xhr.open('方式', url, false ); // 表示发送同步请求