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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
