Home  >  Article  >  Web Front-end  >  An example of how JavaScript uses fetch to complete asynchronous requests

An example of how JavaScript uses fetch to complete asynchronous requests

黄舟
黄舟Original
2017-07-26 16:05:412254browse

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

#fetch is that the syntax is concise and more Semantic

  • Based on standard Promise implementation, supports async/await

  • Isomorphism is convenient

  • But it also has its shortcomings

The fetch request does not carry cookies by default and needs to be set

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

A Promise, when resolved returns the Response object:

Attributes:

status (number)

- HTTP request result parameter, in the range of 100–599
  • statusText (String)

    - Server Returned status report
  • ok (boolean)

    - true if 200 is returned indicating the request is successful
  • headers (Headers)

    -Return header information, detailed introduction below
  • url (String)

    -Requested address
  • Method:

text()

- Generate request text in the form of string
  • json()

    - Generate the result of
  • JSON.parse(responseText)
  • ##blob() - Generate a Blob

  • arrayBuffer() - Generate an ArrayBuffer

  • formData() - Generate formatted data , can be used for other requests

  • Other methods:

clone()

  • Response.error()

  • Response.redirect()

  • response.headers

  • has(name) (boolean) - Determine whether the information header exists

  • get(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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn