Home > Web Front-end > JS Tutorial > A brief introduction to $.ajax, axios and fetch (with code)

A brief introduction to $.ajax, axios and fetch (with code)

不言
Release: 2018-10-16 13:40:46
forward
1656 people have browsed it

This article brings you a brief introduction to $.ajax, axios and fetch (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is Ajax?

Answer: Ajax is a technology that can use asynchronous data transfer (HTTP request) between the browser and the server. Use this to allow a page to request a small amount of data without having to refresh the entire page. For traditional pages (not using Ajax) to refresh part of the content, the entire web page must be reloaded.

What is Ajax based on?

Answer: It is based on XMLHttpRequest (XHR). This is a relatively rough API that does not comply with the design principle of separation of concerns (Separation of Concerns), and is not so friendly to configure and use.

$.ajax’s background?

Answer: Based on the above reasons, various ajax libraries are referenced, but the most famous one is $.ajax() in jQuery API. One of the advantages of $.ajax() is asynchronous operation, but jQuery's asynchronous operation is an event-based asynchronous model, which is not as friendly as promise.

fetch generated background?

Answer: Based on the various factors mentioned above, the fetch API came into being. But it is easy to use, and it has some problems (this problem will be discussed in detail below, and the corresponding solutions will be explained), coupled with compatibility issues (IE does not support it at all), so many developers use axios. Three-party library.

Library that supports promise (axios)?

Answer: The axios library is now a relatively common industry solution. One reason for the popularity of axios is promise, and another reason is the popularity of libraries based on data operations (vue.js, angular.js , react.js, etc.), while traditional jQuery is a library based on DOM operations. But it also has flaws, that is, before we use it, we must ensure that the library has been introduced.

Actually, personally, I still prefer to use fetch. If you encounter compatibility issues during development, you only need isomorphic fetch without introducing an additional library. Let’s focus on fetch.

Usage of fetch

fetch(url, options)
    .then(response => console.log(responese))
    .catch(err => console.log(err))
Copy after login

url: access address
options: common configuration parameters
response: request return object

Request parameters For details on configuring options, please refer to MDN fetch

Fetch problems and solutions

  1. You need two steps to get the data

fetch('https://api.github.com/users/lvzhenbang/repos')
    .then(res => {
        console.log(res)
        return res.text()
    }).then(data => {
        console.log(data)
    })
Copy after login

Through the above code, you can find that there is no data at all in the Response object returned by direct printing. To obtain the required data, you must go through an intermediate method response.text() (provided by fetch 5 methods)

On the other hand, axios is much more convenient to use. The Response object it returns has data in the data attribute. The reference code is as follows:

axios.get('https://api.github.com/users/lvzhenbang/repos')
    .then(res => console.log(res));
Copy after login

Of course, this is not a big problem, but it is a little troublesome to use.

1. The fetch request does not have cookies by default.

To solve this problem, you need to configure {credentials: 'include'} in options

1. Not all requests Errors will be rejected

That is to say, the catch method cannot catch all errors. When the error can be expressed in the form of a status code (such as: 404, 500, etc.), the Promise returned by fetch will not have reject. Catch is only effective when there is a network failure or the request is blocked.

To solve this problem, we can determine whether ok in the Response object is true. If not, use Promise to manually add a reject. The reference code is as follows:

fetch('https://api.github.com/usrs/lvzhenbang/repos')
    .then(res => {
        if (res.ok) {
            return res.text()
        } else {
            return Promise.reject('请求失败')
        }
    }).then(data => {
        console.log(data)
    }).catch(err => {
        console.log(err)
    })
Copy after login

If you do not add reject manually, undefined will be printed, which is not what we want. Of course, using axios, you do not need to consider this issue. The code is as follows:

axios.get('https://api.github.com/usrs/lvzhenbang/repos')
    .then(res => console.log(res))
    .catch(err => console.log(err));
Copy after login

Optimization of fetch

Since the res.text() method returns a promise, .then can be called directly; in addition, in order to ensure that all errors return a unified format (all returns A Promise), the above code can be optimized as follows:

fetch('https://api.github.com/usrs/lvzhenbang/repos')
    .then(res => {
        return res.text()
            .then(data => {
                if (res.ok) {
                    return data
                } elese {
                    return Promise.reject(json)
                }
            })
    }).then(data => {
        console.log(data)
    }).catch(err => {
        console.log(err)
    })
Copy after login

Students who have played express/koa, or have a certain understanding of the backend, know that the server will also return some prompt information in some cases. , so how should we deal with it? Common error prompts include a status code (status) and prompt message (msg). The code is modified as follows:

server:

res.status(404).send({
    err: 'not found'
})
Copy after login

client:

fetch('https://api.github.com/usrs/lvzhenbang/repos')
    .then(handleResponse).then(data => {
        console.log(data)
    }).catch(err => {
        console.log(err)
    })

function handleResponse (res) { 
    return Promise.reject(Object.assign({}, res.text(), {
        status: res.status,
        msg: res.statusText
    }))
}
Copy after login

Compatible Solution

After solving the above problems and optimizing the use of fetch, I found that fetch is still a good choice. The following processing can be done for different usage situations:

Firstly, es5-shim must be introduced to solve the isomorphism of the new feature of fetch;

Secondly, es6-promise must be introduced to solve the compatibility issue of promise;

Then, fetch-ie8 is introduced to solve the isomorphism problem of fech;

Finally, fetch-jsonp is introduced to solve the cross-domain problem.

Of course, you don’t need to solve these problems specifically. The GitHub team provides a polyfill solution, and you don’t need to implement it step by step. Only two steps are needed:

  1. Install fetch package

    npm install whatwg-fetch --save

  2. In The module used imports fetch

import 'whatwg-fetch'

window.fetch(url, options)
Copy after login

and other uses are the same as fetch. The native API is the same.

In which cases you can give up using fetch

Get the status of Promsie, such as: isRejected, isResolved

If you are used to jquery's progress method, or use deffered Some methods

For specific methods similar to jquery implemented by fetch, please refer to whatwg-ftch or fetch-issue

The above is the detailed content of A brief introduction to $.ajax, axios and fetch (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template