Home > Article > Web Front-end > 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();
The current fetch version support details are as follows https://caniuse.com/#search=fetch
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
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
console.log(response.type);//basic is basic.
types are for
如果请求和资源是不同源的,并且返回一个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"); });
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)
来处理下一步的逻辑。
这样做的好处在于能够使得代码更好的维护,可读和测试
对于一个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请求,但是可以设置一个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规范和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!