What are Ajax and fetch? What is the difference between the two?
This article will introduce to you what Ajax and fetch are? What is the difference between Ajax and fetch? , has certain reference value, friends in need can refer to it, I hope it will be helpful to you.
Review XMLHttpRequest
Traditional Ajax refers to XMLHttpRequest (XHR):
var xhr = new XMLHttpRequest()
1. The first requirement The method called is open(), open will not actually send the request
xhr.open("get",url,false) //三个参数:请求方法,请求路径(相对于当前页面),是否异步请求
2. The second method to be called is send(), the request is sent in send
xhr.send(null) //参数:请求发送的主体数据
and the response is received After that, the returned data will automatically populate the xhr object
responseText: the text returned as the response body
responseXML: XML DOM document
status: HTTP status of the response
statusText: HTTP status description
When sending an asynchronous request , we usually detect the readyStatus value of the XHR object:
0: Not initialized, the open() method is not called
1: Startup: open is called, send is not called
2: Send: Call send, but no response is received
3: Accept: Partial data received
4: Complete: All data has been received
load event
onload event handler will receive an event object, and the target attribute points to the XHR object instance, so all methods and properties of the XHR object can be accessed.
XMLHttpRequest does not have the principle of separation of concerns, and the configuration call is very confusing.
The usual writing method is as follows:
var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = function() { console.log(xhr.response); }; xhr.onerror = function() { console.log("Oops, error"); }; xhr.send();
fetch appears
The current fetch version support details are as follows https://caniuse.com/#search=fetch
fetch syntax
The fetch API is designed based on promise
fetch(url, init).then(function(response) { ... });
init optional configuration object, including all request settings:
method: Request method, GET POST, etc.
headers: Request header information, form Is a Headers object or ByteString. body: Requested body information: may be a Blob, BufferSource, FormData, URLSearchParams or USVString object. Note that GET or HEAD method requests cannot contain body information.
mode: Requested mode, see below
credential: By default,
fetch
No cookies will be sent or received from the server, which will result in unauthenticated requests if the site relies on user sessions (to send cookies, the credentials option must be set).omit
: Never send cookies.same-origin
: Only send cookies when the URL has the same origin as the response script, HTTP Basic authentication Wait for verification information.include
: Whether it is a cross-domain request or not, always send verification information such as local cookies and HTTP Basic authentication for the requested resource domain.cache: Requested cache mode: default, no-store, no-cache, force-cache, only-if-cache
Response Metadata
In the above example, you can see that the response is converted to json. If we need other meta-information about the past response, we can use the following methods:
fetch('./test.json').then(function(response) { console.log(response.headers.get('Content-Type'));//application/json console.log(response.headers.get('Date'));//Wed, 5 Sep 2018 09:33:44 GMT console.log(response.status);//200 console.log(response.statusText);//ok console.log(response.type);//basic console.log(response.url)//http://localhost:63342/Apple/test/test.json })
response.headers method:
has(name) (boolean)-determine whether the header information exists
get(name) (string)-Get header information
##getAll(name) (Array)-Get all headers Header information
set(name, value)-Set the parameters of the information header
append(name, value)-Add header content
delete(name)-Delete header information
forEach(function(value, name){ ... }, [thisContext]) - Loop to read header information
In the above example, you can see
console.log(response.type);//basic is basic.
types are for
- If the request and resource are of the same origin, then the request is of basic type, then we can view any content in the response without restrictions
如果请求和资源是不同源的,并且返回一个CORs header的头部,那么请求是
cors
类型。basic
和cors
响应基本相同。但是cors
会限制你查看header中“Cache-Control”,“Content-Language”,“Content-Type”,“Expires”,“Last-Modified”和`Pragma`的属性。如果请求和资源是不同源的,并且不返回一个CORs header头部,那么请求是
opaque
类型。opaque
类型的响应,我们不能过读取任何的返回值或者查看请求状态,这意味着我们无法只知道请求是成功还是失败。
你可以定fetch请求的模式,以便于解析一些模式,如下:
same-origin--同源请求才能成功,其他请求都会被拒绝
cors允许请求同源和其带有合适的CORs头部的其他源
cors-with-forced-preflight--发送真实的请求之前,需要一个预检验
no-cors--旨在向没有CORS header的其他源发出请求并产生不透明opaque的响应,但如上所述,目前在窗口全局范围内这是不可能的。
要定义模式,请在fetch请求中添加选项对象作为第二个参数,并在该对象中定义模式:
fetch('./test.json',{mode:'cors'}) .then(function(response) { console.log(response); return response.json(); }) .then(function(data) { console.log(data); }).catch(function(e) { console.log("Oops, error"); });
fetch基于Promise的调用链
Promise的一个重要特征是链式调用。 对于fetch,这允许你通过fetch请求共享逻辑
fetch('./test.json') .then((response)=>{ if(response.status>=200||response.status<300){ return Promise.resolve(response); } else { return Promise.reject(new Error(response.statusText)) } }) .then((response)=>response.json()) .then((data)=>{ console.log("Response successful json data",data); }) .catch((e)=>{ console.log("Oops, error",e); });
首先定义关于status的方法去检验请求是否成功,并且返回Promise.resolve(response)
和Promise.reject(response)
来处理下一步的逻辑。
这样做的好处在于能够使得代码更好的维护,可读和测试
Post 请求
对于一个web应用,需要通过POST请求和在请求体中添加一些参数去请求API并不罕见
fetch(url, { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: 'foo=bar' }) .then(json) .then(function (data) { console.log('Response successful json data', data); }) .catch(function (error) { console.log('"Oops, error', error); });
关于取消fetch()请求-abort/timeOut
目前没有方法去取消fetch请求,但是可以设置一个timeout选项https://github.com/whatwg/fetch/issues/20
首先实现一个abort功能,fetch返回的是一个promise对象,那么需要在abort后达到出入reject Promise的目的
var abort_fn = null; var abort_promise = new Promise((resolve,reject)=>{ abort_fn=()=>{ reject("abort promise") } })
可以通过调用abort_fn
来触发abort_promise
的reject
fetch返回的promise,称为fetch_promise,那么现在有两个promise:abort_promise
和 fetch_promise
由于每个promise都有reject和resolve回调绑定到哪个promise上呢?
可以采样Promise.race方法
Promise.race
方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.race([p1, p2, p3]); //上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
基于Promise.race的特点,实现方案如下
const p = Promise.race([ fetch_promise, abort_promise ]); p .then(console.log) .catch(console.error);
实现代码
_fetch=(fetch_promise,timeout)=>{ var abort_fn = null; var abort_promise = new Promise((resolve,reject)=>{ abort_fn=()=>{ reject("abort promise") } }) //在这里使用Promise.race var p = Promise.race([ abort_promise, fetch_promise ]) setTimeout(()=>{ abort_fn(); },timeout) return p; } _fetch(fetch('./test.json'),5000) .then((res)=>{ console.log(res) },(err)=>{ console.log(err) })
fetch PK Ajax
fetch规范和Ajax主要有两个方式的不同:
当接收到一个代表错误的 HTTP 状态码时,从
fetch()
返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的ok
属性设置为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。默认情况下,
fetch
不会从服务端发送或接收任何 cookies, 如果站点依赖于用户 session,则会导致未经认证的请求(要发送 cookies,必须设置 credentials 选项)。fetch(url, {credentials: 'include'})
omit
: 从不发送cookies.
same-origin
: 只有当URL与响应脚本同源才发送 cookies、 HTTP Basic authentication 等验证信息.
include
: 不论是不是跨域的请求,总是发送请求资源域在本地的 cookies、 HTTP Basic authentication 等验证信息.
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。更多相关教程请访问AJAX视频教程!
相关推荐:
The above is the detailed content of What are Ajax and fetch? What is the difference between the two?. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











As web applications continue to develop and change, handling parallel and asynchronous requests has become an important topic in PHP backend API development. In traditional PHP applications, requests are performed synchronously, that is, a request will wait until a response is received, which will affect the response speed and performance of the application. However, PHP now has the ability to handle parallel and asynchronous requests. These features allow us to better handle a large number of concurrent requests and improve the response speed and performance of the application. This article will discuss how to deal with PHP backend API development

Recently, during the development of Vue applications, I encountered a common problem: "TypeError: Failedtofetch" error message. This problem occurs when using axios to make HTTP requests and the backend server does not respond to the request correctly. This error message usually indicates that the request cannot reach the server, possibly due to network reasons or the server not responding. What should we do after this error message appears? Here are some workarounds: Check your network connection due to

How to solve the problem of real-time update of asynchronous request data in Vue development. With the development of front-end technology, more and more web applications use asynchronous request data to improve user experience and page performance. In Vue development, how to solve the problem of real-time update of asynchronous request data is a key challenge. Real-time update means that when the asynchronously requested data changes, the page can be automatically updated to display the latest data. In Vue, there are multiple solutions to achieve real-time updates of asynchronous data. 1. Responsive machine using Vue

UniApp error: 'xxx' asynchronous request failed solution With the rapid development of mobile applications, UniApp, as a cross-platform development framework, is increasingly favored by developers. However, like any other technical framework, UniApp also has some potential problems, one of which is the problem of error reporting when asynchronous requests fail. This article will introduce some common reasons why UniApp reports error: "'xxx' asynchronous request failed" and provide some solutions. First, we need to understand what an asynchronous request is. in U

In today's Internet era, many applications need to make network requests to obtain or send data. HTTP requests are one of the most commonly used network request methods. In the Go language, we can use the net/http package in the standard library to initiate HTTP requests, but this will block the current coroutine. So how to implement asynchronous HTTP requests in Go language? This article will introduce two methods of implementing asynchronous HTTP requests in the Go language. Method 1: Use goroutine and channelGorout

In Vue project development, data request and processing are very important links. A good data request and processing strategy can greatly improve application performance and user experience. This article will share some experiences in data request and processing in Vue project development. Proper use of the Axios library Axios is a commonly used Promise-based HTTP library for sending XHR requests. In a Vue project, you can use Axios to send data requests. When using Axios, you need to pay attention to the following points: Properly configure A

Asynchronous request processing problems encountered in Vue technology development require specific code examples. In Vue technology development, asynchronous request processing is often encountered. Asynchronous requests mean that while sending a request, the program does not wait for the return result and continues to execute subsequent code. When processing asynchronous requests, we need to pay attention to some common issues, such as the order of processing requests, error handling, and concurrent execution in asynchronous requests. This article will combine specific code examples to introduce the asynchronous request processing problems encountered in Vue technology development and give

Vue is an extremely popular front-end framework, and Axios is currently a popular front-end asynchronous request library. This article will introduce in detail how to use Axios to send asynchronous requests in Vue. Installation and use of Axios Axios is a Promise-based HTTP client for sending asynchronous requests. We can install it via npm: npminstallaxios and then we can use it in Vue, first we need to import it in the component: importax
