Home >Web Front-end >JS Tutorial >How does promise encapsulate ajax? Implementation method of promise encapsulation ajax

How does promise encapsulate ajax? Implementation method of promise encapsulation ajax

不言
不言Original
2018-09-19 17:36:013321browse

The content of this article is about how promise encapsulates ajax? The implementation method of promise encapsulating ajax has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First post the code

var ajaxOptions = {
    url: 'url',
    method: 'GET',
    async: true,
    data: null,
    dataType: 'text',
}

function ajax(protoOptions) {
    var options = {};

    for(var i in ajaxOptions){
        options[i] = protoOptions[i] || ajaxOptions[i];
    }
    

    return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();

        xhr.open(options.method, options.url, options.async);

        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                resolve(this.responseText, this);
            } else {
                var resJson = {
                    code: this.status,
                    response: this.response
                }
                reject(resJson, this)
            }
        }

        xhr.send()

    })
}

Comments:

1, open(method, url, async)

Method: GET and POST;

url: URL sent to the server;

async: asynchronous true, synchronous false;

2,onreadystatechange

Whenever the value of readyState changes, the onreadystatechange function is automatically executed

3, readyState server response status information

  • 0: The request is not initialized

  • 1: The server connection has been established

  • 2: The request has been received

  • 3: The request is being processed

  • 4: The request has been completed and the response is ready

When the value of readyState is 4 and the status is 200, it means that the corresponding response is ready and a successful call can be executed. method, otherwise the method that fails to be called

The above is the detailed content of How does promise encapsulate ajax? Implementation method of promise encapsulation ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn