Home >Web Front-end >JS Tutorial >Native JS encapsulation of AJAX methods

Native JS encapsulation of AJAX methods

Guanhui
Guanhuiforward
2020-05-05 09:52:152392browse

Ajax is used by everyone every day. The jquery library's encapsulation of Ajax is also very complete and easy to use. Let's take a look at its internal principles and manually encapsulate an Ajax library of our own.

1. Principle

Sending native Ajax requires four steps:

1) Create Ajax object: XMLHttpRequest

2) Set request parameters: open(request parameters [get/post], url address, asynchronous or not [true/false] )

3) Set callback function: onreadystateChange is used to process the returned data

4) Send a request: send()

//TODO step1: 创建ajax对象
var xhr = new XMLHttpRequest();
//TODO step2: 设置请求参数
xhr.open('get','01.php',true);
//TODO step3: 设置回调
xhr.onreadystatechange = function () {
    //接收返回数据
    console.log(xhr.responseText);//responseText 用于接收后台响应的文本
}
//TODO step4: 发送请求
xhr.send();

2. Encapsulation

The core idea of ​​encapsulation is to treat the parts that need to be dynamically changed as parameters, and leave the unchanged parts There, in the above code, the request method (get, post), request address url, request parameter data, successful callback success, failed callback error, etc., these parameters are dynamically changed; while creating the Ajax object XMLHttprequest, event monitoring onreadystatechange, etc. are fixed, so the first step is to determine the encapsulation parameters:

v url request address

v data request data

v type request type

v success success callback

v error failure callback

v beforeSend is called before sending return false to prevent sending

v complete callback for ajax request success, no matter when Will be executed

function ajax(option){
    //用户配置option 默认配置init
    var init = {
        type:'get',
        async:true,
        url:'',
        success: function () { },
        error: function () { },
        data:{},
        beforeSend: function () {
            console.log('发送前...');
            return false;
        }
    };
    //TODO step1: 合并参数
    for(k in option){
        init[k] = option[k];
    }
    //TODO step2: 参数转换
    var params = '';
    for(k in init.data){
        params += '&'+k+'='+init.data[k];
    }
    var xhr = new XMLHttpRequest();
    // type url
    //TODO step3: 区分get和post,进行传参
    var url = init.url+'?__='+new Date().getTime();
    //TODO step4: 发送前
    var flag = init.beforeSend();
    if(!flag){
        return;
    }
    if(init.type.toLowerCase() == 'get'){
        url += params;
        xhr.open(init.type,url,init.async);
        xhr.send();
    }else{
        xhr.open(init.type,url,init.async);
      xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(params.substr(1));
    }
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                init.success(xhr.responseText);
            }else{
                //error
                init.error();
            }
        }
    }
}

What we should pay attention to here is that the parameter passing methods of get and post are different. The get request needs to be directly spliced ​​after the url address, and the post request needs to pass parameters in the send method, and this needs to be The request header is setRequestHeader('content-type','application/x-www-form-urlencoded'), so it needs to be distinguished when encapsulating.

Due to too many parameters, users do not need to pass in many parameters every time, otherwise it will be very cumbersome to use. Therefore, we adopt the form of default parameters. If the user does not pass in the parameter, the default value will be used. If the user does not pass in the parameter, the user's parameter will be used.

3. Usage examples

ajax({
    url: 'test.json',
    data:{test:123,age:456},
    //type:'post',
    success: function (res) {
        console.log(res);
    }
});

The above is the detailed content of Native JS encapsulation of AJAX methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:zhihu.com. If there is any infringement, please contact admin@php.cn delete