Finally understand how to write native AJAX

Interview frequently asked questions ---- handwritten native AJAX. The following is a personal summarize, we want to help.


One) native JavaScript Utsushide AJAX

First, we analyze the appropriate steps according to the document. Step 1: Create Object Step: Initialization Step HTTP request parameters: sending a request Step four: listen request state, the callback function executes a corresponding

Pre-knowledge

Every state change event onreadystatechange event triggered.

responseText response received from the server body (excluding the head), or if the data has not been received, then, is an empty string.

responseXML response to the request, parses the XML Document Object and returned as the.

status from numeric code returned by the server, such as the common 404 (Not Found) and 200 (ready)

request status Text HTTP status code

the readyState HTTP request state. When an XMLHttpRequest first created, the value of this attribute from zero, until a complete HTTP response, this value is increased to 4.

0 (uninitialized) object has been created, but has not been initialized (open method has not been called)

1 (initialization) object has been established, send method has not been called

2 (transmission data) Send method has been called, but the current state of the http header and unknown

3 (data transmission) received partial data, because the response http header and incomplete, and responseBody time acquired by the partial data error occurs responseText

4 (complete) data has been received, this time for obtaining a complete response and responseText data responseXml

Remember this picture

The object is created

IE5,6 not compatible with XMLHttpRequest, so use ActiveXObject () object, and pass 'Microsoft.XMLHTTP', to achieve compatibility purposes.

    var xhq = null
    if (XMLHttpRequest) {
        xhq = new XMLHttpRequest() // 创建对象
    } else {
        xhq = new ActiveXObject("Microsoft.XMLHTTP") // 兼容IE5、6
    }
复制代码

2, the initialization parameter HTTP request

Syntax: open (method, url, async, username, password) Parameters: Type Value Required method request includes a path of GET, POST and HEAD requests require mandatory url async alternative path to the requested server request the default is true is the asynchronous optional authentication username and password required for the request

Meanwhile, the request will readyState to 1, and the responseText, responseXML, status and statusText parameters to their default values.

xhq.open('get', 'https://www.easy-mock.com/mock/5cf7654cf8ab93502742fb99/example/query', true)
复制代码

Here analog interface easy-mock.

3, sending the request

Syntax: send (body) Parameter Description: An optional list of parameters passed

  xhq.send({
        username: '123'
    })
复制代码

After the request, send () will readyState is set to 2, and trigger onreadystatechange event.

When all the HTTP response headers have been received, send () or background thread sets readyState 3 and trigger onreadystatechange event.

When the response is complete, send () or background thread sets readyState is 4, and the last time trigger events.

4, the state monitor request, the callback function executes a corresponding

When readyState is 4, and the server 200 in response to

    xhq.onreadystatechange = function () {
        if ( xhq.readystate == 4 && xhq.status == 200 ) {
            // success 回调
            success(xhq.responseText)
        }  else if (xhq.readyState == 4 && xhq.status !== 200) {
            // error 回调
            error()
        }
    }
复制代码

To function as a way to merge all content


function sendAjax(obj) {
// get方式传入时,将内容进行data内容进行拼接
    function splicStr(data) {
        var str = ''
        for (var i in data) {
            str = i + '=' + data[i]
        }
        return str
    }
// 原生ajax实现 步骤分析
// 一、声明XMLHttpRequest, 为了兼容IE5、6需要使用ActiveXObject()
    var xhq = null
    if (XMLHttpRequest) {
        xhq = new XMLHttpRequest() // 创建对象
    } else {
        xhq = new ActiveXObject("Microsoft.XMLHTTP") // 兼容IE5、6
    }
// 二、初始化HTTP请求参数, 只初始化并不会发送
    if (obj.method.toUpperCase() === 'GET') { // get方法
        xhq.open(obj.method, obj.url + '?' + splicStr(obj.data),  typeof obj.async === 'boolean'? obj.async : true) // 路径拼接
        // 三、发送此次请求
        xhq.send()
    }
    else if (obj.method.toUpperCase() === 'POST') { // post方法
        xhq.open(obj.method, obj.url, typeof obj.async === 'boolean'? obj.async : true)
        xhq.setRequestHeader("content-type","application/x-www-form-urlencoded") // 以表单提交
        // 三、发送此次请求
        xhq.send(obj.data)
    }


//四、监听发送
    xhq.onreadystatechange = function () {
        if ( xhq.readyState == 4 && xhq.status == 200 ) {
            // success 回调
            success(xhq.responseText)
        } else if (xhq.readyState == 4 && xhq.status !== 200) {
            // error 回调
            error()
        }
    }
}

sendAjax({
    url: 'your url',
    method: 'post',
    async: true,
    data: {
        username: 'xiong',
        pwd: '123'
    },
    success: function (data) {
        console.log(data)
    },
    error: function () {
        console.log('发生了错误')
    }
})
复制代码

Prototype constructed in the manner of merger

function sendAjax(obj) {
    this.xhq = null
    this.method = obj.method || 'get'
    this.url = obj.url
    this.data = obj.data
    this.async = typeof obj.async === 'boolean'? obj.async : true
    this.success = obj.success
    this.error = obj.error
    this.init()
}
sendAjax.prototype = {
    init: function () {
        if (XMLHttpRequest) {
            this.xhq = new XMLHttpRequest() // 创建对象
        } else {
            this.xhq = new ActiveXObject("Microsoft.XMLHTTP") // 兼容IE5、6
        }
        this.openReq()
        this.watchReq()
    },
    openReq: function () {
        if (this.method.toUpperCase() === 'GET') { // get方法
            this.xhq.open(this.method, this.url + '?' + this.splicStr(this.data), this.async) // 路径拼接
            // 三、发送此次请求
            this.xhq.send()
        }
        else if (this.method.toUpperCase() === 'POST') { // post方法
            this.xhq.open(this.method, this.url, this.async)
            this.xhq.setRequestHeader("content-type","application/x-www-form-urlencoded") // 以表单提交
            // 三、发送此次请求
            this.xhq.send(this.data)
        }
    },
    watchReq: function () {
        var that = this
        this.xhq.onreadystatechange = function () {
            if ( that.xhq.readyState == 4 && that.xhq.status == 200 ) {
                // success 回调
                that.success(that.xhq.responseText)
            } else if (that.xhq.readyState == 4 && that.xhq.status !== 200) {
                // error 回调
                that.error()
            }
        }
    },
    splicStr: function (data) {
        var str = ''
        for (var i in data) {
            str = i + '=' + data[i]
        }
        return str
    }
}
new sendAjax({
    url: 'https://www.easy-mock.com/mock/5cf7654cf8ab93502742fb99/example/query',
    method: 'get',
    async: true,
    data: {
        username: 'xiong',
        pwd: '123'
    },
    success: function (data) {
        console.log(data)
    },
    error: function () {
        console.log('发生了错误')
    }
})
复制代码

Case does not handle all possible, but enough basic use. Bear Kat wish you happy learning.

Content of the article draws W3school about XMLHttpRequest document

Reproduced in: https: //juejin.im/post/5d007134e51d45590a445b23

Guess you like

Origin blog.csdn.net/weixin_34320724/article/details/93174750