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))
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
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) })
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));
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) })
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));
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) })
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' })
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 })) }
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:
-
Install fetch package
npm install whatwg-fetch --save
In The module used imports fetch
import 'whatwg-fetch' window.fetch(url, options)
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
