JS asynchronous request

asynchronous request

Compared with traditional synchronous requests (often accompanied by page jumps), it is more efficient and can continue to process web pages during the request process. Asynchronous
requests can realize partial refresh of pages and save bandwidth

working principle

Implementation of asynchronous requests

  • Native JS (understand)

  • jquery ajax (using the jQuery library)

  • fetch (newly added by ES6, which needs to be mastered in this project)

  • axios (more powerful axios library)

  • other methods

Native JS realizes asynchronous request

One core object, three methods, four attributes

// 1. 创建一个核心对象  XMLHttpRequest (不支持低版本的IE)

let xhr = false ;
try{
    xhr = new XMLHttpRequest();
}catch(e) {
    // 使用 IE 创建方式
    xhr  = new ActiveXObject("microsoft.XMLHTTP") ;
}


// 2. 和服务器建立链接
// url : 代表要访问的 请求地址 
// method : 代表要方法的 请求方式
xhr.open(method , url);


// 3. 设置请求的头信息
// name = Content-Type , value 值为 application/x-www-form-urlencoded
xhr.setRequestHeader(name , value) 

// 4. 发送请求到服务器 ,并可以携带数据 
// param 是一个字符串,参数的个格式  a=1&b=2&c=3,  POST请求才支持传参, 如果没有参数,设置未 null 即可
xhr.send(param)


// 5. 通过 onreadystatechange 监听服务器响应信息 , 值是一个回调函数

xhr.onreadystatechange = function() {

    // 6.  获取 客户端和服务器 的链接状态 
    /*
        xhr.readyState 有 5个值 
            0 : 未建立链接, xhr 还没有调用 open 方法
            1 : 链接已建立, xhr 已经调用了 open 方法
            2 :  请求已发送, xhr 已经调用了 send 方法
            3 :  服务器正在处理数据、但未完成响应
            4 :  服务器已响应完成 
    */
    let  state = xhr.readyState ; 
    
    
    // 判断 状态是否4 
    if (state == 4)  {
            // 获取 服务器 返回的状态码  xhr.status
            /**
                200 : 服务器正常响应数据 
                201 : 新增数据成功
                204 : 没有内容, 一般用于 删除成功
                301/302 : 永久/临时 重定向
                304 : 数据没有改变,通常代表 浏览器缓存了数据
                400 :  通常是请求参数 不正确 
                401 :  没有认证 (访问没有授权的资源)
                403 :  禁止访问 
                404 :  页面找不到 
                405 :  请求方式不正确
                500 :  服务器代码产生异常
            */
            if (xhr.status == 200) {
                   
                   // 获取 服务器响应的数据, 返回的是一个 字符串
                  xhr.responseText  
            }
    
    }
    
}

ES6 uses fetch to implement asynchronous requests

  • get request
fetch(url)
    .then(response => response.json())
    .then(data => {  ... })   // data 就是 接口返回的 JSON数据

The result returned by fetch is a Promise (commitment) object. If it is successfully processed by then, the failure is processed by catch.
then() represents the callback function executed after successfully obtaining the result, so a callback function in then needs to be passed in to
then A response response object will be passed in, because the data format returned by an asynchronous request is usually in json format, so return response.json() in the callback function of then to continue calling then or catch catch() on
the result returned by then to indicate failure
Get the callback function executed by the result, catch requires passing in a callback function
then() / catch() The result returned by the method is still a Promise object

When fetch calls then for the first time, no matter what the status code returned by the request is, it will enter. Only when the interface cannot be accessed will the catch be executed, so developers usually need to process the status code in the first then

  • post request
var form = document.querySelector('form')

fetch('/users', {
  method: 'POST',
  body: new FormData(form)
})

Guess you like

Origin blog.csdn.net/weixin_52953038/article/details/127232391