ajax to fetch and axios

1- AJAX asynchronous principle and implementation

Ajax works between the user and the server corresponds to the addition of an intermediate layer (Ajax engine), so that the user of the asynchronous operation of the server response. Not all user requests are submitted to the server, such as - some data validation (such as whether the user entered data) and data processing (such as whether the user input data is digital) to do so to their own Ajax engine, only to determine submit a new request needs to read data from the server to the server on behalf by the Ajax engine. These to the Ajax engine users to operate it feel more fluent.

Read the information online predecessors wrote, I summarized ajax principles and processes as follows:

1, AJAX to create an asynchronous XMLHttpRequest Object

This is the core of the ajax object, the following code is the chrome browser and browser version compatible with IE

var ajax = {};
ajax.httpRequest = function () {
    //判断是否支持XMLHttpRequest对象
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    //兼容IE浏览器
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"
    ];
    //定义局部变量xhr,储存IE浏览器的ActiveXObject对象
    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
    return xhr;
};

复制代码

2, Ajax advantages and disadvantages

Ajax's advantage

1.无刷新更新数据。
2.异步与服务器通信。
3.前端和后端负载平衡。
4.基于标准被广泛支持。
5.界面与应用分离。
复制代码

Ajax shortcomings

1.AjAX干掉了Back和加入收藏书签功能,即对浏览器机制的破坏。
2.AJAX的安全问题。
3.因为网络延迟需要给用户提供必要提示
复制代码

2- operation XMLHttpRequest object

Ajax (Asynchronous JavaScript and XML) does not refer to one single technology, but rather a series of related organic use of technology. Despite its name, comprising the XML, but in fact can be replaced by the JSON format data, to further reduce the amount of data, a so-called AJAJ. To use the JavaScript HTTP request to the server instance of the class that provides this functionality requires. This is the origin of XMLHttpRequest. Such a class was originally introduced as of the XMLHTTP ActiveX object named in Internet Explorer. Then, Mozilla, Safari and other browsers, implement an XMLHttpRequest classes, methods and properties to support Microsoft's original ActiveX object. At the same time, Microsoft also realized XMLHttpRequest.

1, using xhr object.

(1)设置请求参数(请求方式,请求页面的相对路径,是否异步)
(2)设置回调函数,一个处理服务器响应的函数,使用 onreadystatechange ,类似函数指针
(3)获取异步对象的readyState 属性:该属性存有服务器响应的状态信息。每当 readyState 改变时,onreadystatechange 函数就会被执行。
(4)判断响应报文的状态,若为200说明服务器正常运行并返回响应数据,
(5)读取响应数据,可以通过 responseText 属性来取回由服务器返回的数据。
复制代码

2, XMLhttpRequest property

onreadystatechange

A JavaScript function object, when the readyState property changes would call it. The callback function will be called user interface thread.

readyState

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

Five states in an informal name of each has an associated, the following table lists the status, name and meaning:

status name description
0 Uninitialized Initialization state. XMLHttpRequest object has been created or has been reset abort () method.
1 Open open () method has been called, but send () method is not called. Request has not been sent.
2 Sent Send () method has been called, HTTP request has been sent to the Web server. Response is not received.
3 Receiving All response headers have been received. In response to start receiving the body but not completed.
4 Loaded HTTP response has been completely received.

ReadyState value is not decremented, except when a time in the method of processing the call request abort () or open (). Every time the value of the property increases, will trigger onreadystatechange event handler.

responseText

So far as the server receives the response body (excluding the head), or if the data has not been received, then, it is an empty string.

If readyState is less than 3, the property is an empty string. When readyState is 3, this property returns a response has been received in the current section. If readyState is 4, this property contains the complete response body.

If the response contains the specified character encoding in response to the head body, on the use of this encoding. Otherwise, it is assumed that Unicode UTF-8.

responseXML

Response to the request, and returns the XML is parsed as Document object.

status

HTTP status code returned by the server, such as 200 indicates success, while 404 indicates "Not Found" error. When less than 3 readyState read this property causes an exception.

statusText

The attribute names rather than with the HTTP request specifies the status code. That is, when the state 200 when it is "OK", when the state 404 when it is "Not Found". And status attributes, when less than 3 readyState read this property causes an exception.

3, XMLHttpRequest method

abort()

Cancel the current response, closes the connection and the end of any pending network activity.

The method of the XMLHttpRequest object readyState is reset to 0 state, and cancels all pending network activity. For example, if the request is too long, and the response is no longer necessary, you can call this method.

getAllResponseHeaders ()

The string is returned as the HTTP response header unresolved.

If readyState is less than 3, this method returns null. Otherwise, it returns all HTTP response header sent by the server. It returned as a single string head, a line head. Each row with newline "\ r \ n" spaced apart.

getResponseHeader()

Returns the specified value of the HTTP response header. Its argument is to return the name of the HTTP response header. You can use any development of this case to the head of the name, and respond to head comparison is not case sensitive.

The return value is the specified value of the HTTP response header, this header is not received or is less than 3 readyState empty string. If a head is received a plurality of the specified name, this value header is returned and connected, using a comma and a space separated from each header value.

open()

The method initiates a request for JavaScript code; Instead If local code, OpenRequest ()) method.

Note: (request has been called open () or openRequest () method) has been activated in a request to call this method again equivalent to calling the abort () method.

parameter

  • method

The method of HTTP request used; for example "GET", "POST", "PUT", "DELETE", etc. If the argument is non-HTTP (S) of the URL, the parameter is ignored.

  • url

The request to access the URL

  • async

An optional boolean parameter, the default is true, meaning whether an asynchronous operation, if false, the send () method does not return anything until the server receives the returned data. If value is true, a clear notice to the developer will be sent to the relevant event listener. This value must be true, if the multipart attribute is true, otherwise there will be an accident.

  • user

User name, optional parameter, used under license; the default parameter is an empty string.

  • password

Password, optional parameter, used under license; the default parameter is an empty string.

send()

HTTP request, passed to the open () method parameters, and passed to the alternative method of the request body.

setRequestHeader()

But to open a transmission setting request HTTP request or addition of one (setting request header). parameter

  • header

Request header name to be assigned

  • value

The value assigned to the specified request header

4, primeval Js basis ajax

ajax.send = function (url, callback, method, data, async) {
    //默认异步
    if (async === undefined) {
        async = true;
    }
    var httpRequest = ajax.httpRequest();
    //初始化HTTP请求
    httpRequest.open(method, url, async);
    //onreadystatechange函数对象
    httpRequest.onreadystatechange = function () {
        //readyState 的值等于4,从服务器拿到了数据
        if (httpRequest.readyState == 4) {
            //回调服务器响应数据
            callback(httpRequest.responseText)
        }
    };
    if (method == 'POST') {
          //给指定的HTTP请求头赋值
        httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
      //发送HTTP请求
    httpRequest.send(data);
};
//实现GET请求
ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
//实现POST请求
ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};

复制代码

5, jQuery's ajax

    $.ajax({
        type: "", 请求方式
        url: "", // 请求路径
        async: true, // 默认是异步
        data: JSON.stringify({ obj }),
        contentType: 'application/json;charset=utf-8', // 设置contentType
        success: function(res) { 
            console.log(res)
        },
        error: function(err) {
            console.log(err)
        }
        
    )
复制代码

6, JSON format

Online check JSON formatting tools

1、key添加双引号
2、末尾没有分号
3、同一个对象不允许有两个同名属性
复制代码

Serialization

JSON.stringify() // JSON对象转换成JSON字符串
JSON.parse()     // JSON对象转换成JSON字符串
复制代码

3- fetch

ajax fetch claims to be a substitute for, its API is based on the design of the Promise, the old version of the browser does not support Promise, it requires the use of polyfill es6-promise

// 原生XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)   // 从服务器获取数据
    }
}
xhr.send()
// fetch
fetch(url)
    .then(response => {
        if (response.ok) {
            response.json()
        }
    })
    .then(data => console.log(data))
    .catch(err => console.log(err))

复制代码

On MDN, I talked about it with jquery ajax difference, which is also fetch very strange place:

When receiving a HTTP status code indicating an error, () returned from fetch Promise not flagged as reject, even if the status code of the HTTP response is 404 or 500. Instead, it is marked as a state Promise resolve (but ok resolve property will be set to the return value to false), only when a network failure or the request is blocked, it will be labeled as reject. By default, fetch does not send or receive any cookies from the server, if the site depends on the user session, the request will result in non-certified (to send cookies, you must set credentials option).

Suddenly feel this jquery ajax not as easy to use it? Do not worry, and then with the async / await will make our asynchronous code more elegant:

async function test() {
    let response = await fetch(url);
    let data = await response.json();
    console.log(data)
}

复制代码

It looks like synchronization code is not the same? Just perfect! Well, it is not perfect, async / await ES7 is the API, currently still in the experimental stage, we also need to be translated using the babel ES5 code.

Also like to mention that, fetch is a relatively low-level API, in many cases we need to be resealed. such as:

// jquery ajax
$.post(url, {name: 'test'})
// fetch
fetch(url, {
    method: 'POST',
    body: Object.keys({name: 'test'}).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
    }).join('&')
})

复制代码

Since the bottom is relatively fetch API, so we need to manually spliced ​​into the parameter 'name = test' format, and has a good package jquery ajax. So fetch is not out of the box.

In addition, fetch does not support timeout control.

Oh, I feel good garbage fetch ah, also need to continue to grow. .

4- axios

axios God is great, especially rain the river is recommended, it is also encapsulate the native XHR. It has the following major features:

  • Can be used in node.js
  • Providing an interface concurrent requests
  • Support Promise API

Simple to use

axios({
    method: 'GET',
    url: url,
})
.then(res => {console.log(res)})
.catch(err => {console.log(err)})
复制代码

Parallel development

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
复制代码

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

Guess you like

Origin blog.csdn.net/weixin_34245082/article/details/91464651