Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the new way to write fetch_ajax request in XMLHttpRequest

Shulou Source: shulou.com Published: 2022-06-02 17:56:46 10月14日 Update

This article mainly explains "what is the new writing method of fetch_ajax request in XMLHttpRequest". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the new writing method of fetch_ajax request in XMLHttpRequest"?

The fetch () function is an Promise-based mechanism for programmatically generating Web requests in browsers. The project is a polyfill that implements a subset of the standard Fetch specification and is sufficient to provide a viable alternative to most uses of XMLHttpRequest in traditional fetch Web applications.

Fetch installation method:

The de facto standard, which does not exist in the ES6 specification, is implemented based on Promise. At present, there are still some problems in the compatibility of Promise in the project. If fetch is applied in the project, es6-promise and fetch need to be introduced.

Install whatwg-fetch (like ajax, the new way to get data, support promise syntax) to get data.

Npminstallwhatwg-fetch--save

Or

Bowerinstallfetch.

Current location: lazy people build sites > javascript tutorials > usage of fetch (fetch new generation ajax request scheme)

Basic Fetch request

Let's first compare an example of using XMLHttpRequest with an example of using the fetch method. The example makes a request to the server, gets the response, and parses it using JSON.

XMLHttpRequest

A XMLHttpRequest needs to set up two event callback functions, one to be called if the data is successful and the other to be called when it fails to get the data, as well as an open () method call and a send () method call.

FunctionreqListener () {

Vardata=JSON.parse (this.responseText)

Console.log (data)

}

FunctionreqError (err) {

Console.log ("Fetch error:" + err)

}

VaroReq=newXMLHttpRequest ()

OReq.onload=reqListener

OReq.onerror=reqError

OReq.open ("get", "/ students.json", true)

OReq.send ()

Thank you for your reading, the above is the content of "what is the new writing of fetch_ajax request in XMLHttpRequest". After the study of this article, I believe you have a deeper understanding of what the new writing of fetch_ajax request in XMLHttpRequest is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Writing data method example project learning content function way tone standard problem application feasibility success two event fact tradition location Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MySQL Xiaomi Apple Redmi