


An example of how JavaScript uses fetch to complete asynchronous requests
Transmitting information to the server and obtaining information from the server are the top priorities of front-end development, especially under the premise of separation of front-end and back-end. Data interaction between front-end and back-end is a compulsory subject for the front-end. The following article mainly provides We have introduced relevant information about JavaScript using fetch to implement asynchronous requests. Friends in need can refer to it.
Preface
I believe everyone should know that in this AJAX era, if you want to make API and other network requests, you must use XMLHttpRequest or The encapsulated framework makes network requests. The fetch framework produced now is simply designed to provide more powerful and efficient network requests. Although there are some browser compatibility issues at present, when we make some asynchronous requests, we can use fetch to make perfect network requests. Not much to say below, let’s take a look at the detailed introduction.
Let’s first take a look at the native support for fetch in each browser. You can see that the support is not very high. Safari only supports it after 10.1, ios only supports it after 10.3, and IE does not support it at all. Of course, the development of new technologies will always go through this process.
Ajax request
Ordinary Ajax request, send one using XHR A json request generally looks like this:
var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = 'json'; xhr.onload = function(){ console.log(xhr.response); }; xhr.onerror = function(){ console.log("error") } xhr.send();
Use fetch to implement:
##
fetch(url).then(function(response){ return response.json(); }).then(function(data){ console.log(data) }).catch(function(e){ console.log("error") })You can also use async/ The way of await
try{ let response = await fetch(url); let data = await response.json(); console.log(data); } catch(e){ console.log("error") }After using await, writing asynchronous code feels as good as synchronous code. Await can be followed by a Promise object, which means waiting for
Promise resolve() before continuing to execute. If Promise is
reject() or throws an exception, it will be blocked by an external try... catch capture.
The main advantage of using fetch
- Based on standard Promise implementation, supports async/await
- Isomorphism is convenient
- But it also has its shortcomings
fetch(url, {credentials: 'include'})
The server will not reject when it returns an error code such as 400 or 500. Only when network errors cause the request to fail to be completed, fetch will be rejected.
- fetch Syntax:
fetch(url, options).then(function(response) { // handle HTTP response }, function(error) { // handle network error })
Specific parameter example:
//兼容包 require('babel-polyfill') require('es6-promise').polyfill() import 'whatwg-fetch' fetch(url, { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, credentials: "same-origin" }).then(function(response) { response.status //=> number 100–599 response.statusText //=> String response.headers //=> Headers response.url //=> String response.text().then(function(responseText) { ... }) }, function(error) { error.message //=> String })
Parameter description
url
Define the resource to be obtained. This might be: a USVString string containing the URL to fetch the resource. A Request object.options (optional)
A configuration item object, including all settings for the request. Optional parameters are:#method: The method used for the request, such as GET and POST.
- headers: Header information of the request, in the form of 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, such as cors, no-cors or same-origin.
- credentials: Requested credentials, such as omit, same-origin or include.
- cache: Requested cache mode: default, no-store, reload, no-cache, force-cache, or only-if-cached.
response
Attributes:
status (number)
- HTTP request result parameter, in the range of 100–599-
- Server Returned status reportstatusText (String)
-
- true if 200 is returned indicating the request is successfulok (boolean)
-
-Return header information, detailed introduction belowheaders (Headers)
-
-Requested addressurl (String)
Method:
text()
- Generate request text in the form of string-
- Generate the result ofjson()
JSON.parse(responseText) ##blob()
- Generate a BlobarrayBuffer()
- Generate an ArrayBufferformData()
- Generate formatted data , can be used for other requestsOther methods:
Response.error()
Response.redirect()
response.headers
has(name) (boolean)
- Determine whether the information header existsget(name) (String)
- 获取信息头的数据getAll(name) (Array)
- 获取所有头部数据set(name, value)
- 设置信息头的参数append(name, value)
- 添加header的内容delete(name)
- 删除header的信息forEach(function(value, name){ ... }, [thisContext])
- 循环读取header的信息
使用实例
//获取css里ul的id属性 let uldom = document.getElementById("students"); //单独创建一个json文件,获取地址 let url = "data.json"; function main(){ fetch(url).then(respone=>{ return respone.json(); }).then(students=>{ let html = ``; for(let i=0, l=students.length; i<l; i++){ let name = students[i].name; let age = students[i].age; html += ` <li>姓名:${name},年龄:${age}</li> ` } uldom.innerHTML = html; }); } main();
结合await最终代码
let uldom = document.getElementById("students"); let url = "data.json"; async function main(){ let respone = await fetch(url); let students = await respone.json(); let html =``; for(let i=0, l=students.length; i<l; i++){ let name = students[i].name; let age = students[i].age; html += ` <li>姓名:${name},年龄:${age}</li> ` } uldom.innerHTML = html; } main();
data.json文件内容如下:
[ {"name":"张三","age":"3"}, {"name":"李万","age":"1"}, {"name":"王二","age":"4"}, {"name":"二狗","age":"3"}, {"name":"狗蛋","age":"5"}, {"name":"牛娃","age":"7"} ]
运行后结果是:
姓名:张三,年龄:3 姓名:李万,年龄:1 姓名:王二,年龄:4 姓名:二狗,年龄:3 姓名:狗蛋,年龄:5 姓名:牛娃,年龄:7
The above is the detailed content of An example of how JavaScript uses fetch to complete asynchronous requests. For more information, please follow other related articles on the PHP Chinese website!

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

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


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

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.
