Ajax request
For ordinary Ajax requests, sending a json request with XHR 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();
The way to use fetch:
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 / 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 cool as synchronous code. Await can be followed by a Promise object, which means that it will wait for the Promise resolve () to continue execution. If the Promise is rejected () or throws an exception, it will be caught by the outer try ... catch.
Use fetch
The main advantages of fetch are:
- Concise syntax, more semantic
- Convenient isomorphism
- But it has its shortcomings
But it has its shortcomings:
- fetch requests do not have cookies by default, you need to set fetch (url, {credentials: 'include'})
- The server will not reject when it returns an error code of 400,500. Only when network errors cause the request to fail to complete, fetch will be rejected.
fetch syntax:
fetch(url, options).then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})
Specific parameter cases:
// Compatible package
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 resources to get. This could be: a USVString string containing the URL of the resource to be fetched. A Request object.
options (optional)
A configuration item object, including all the settings for the request. The optional parameters are:
method: The method used for the request, such as GET, POST.
headers: Requested header information, in the form of Headers object or ByteString.
body: the requested body information: it may be a Blob, BufferSource, FormData, URLSearchParams or USVString object. Note that requests for GET or HEAD methods cannot include body information.
mode: The requested mode, such as cors, no-cors, or same-origin.
credentials: The requested credentials, such as omit, same-origin, or include.
cache: The requested cache mode: default, no-store, reload, no-cache, force-cache, or only-if-cached.
response
A Promise that returns a Response object when it resolves:
Attributes:
status (number)-HTTP request result parameter, in the range 100–599
statusText (String)-status report returned by the server
ok (boolean)-true if 200 is returned indicating the request was successful
headers (Headers)-return header information, detailed below
url (String)-the requested address
method:
text ()-Generate request text as a string
json ()-Generate the result of JSON.parse (responseText)
blob ()-Generate a blob
arrayBuffer ()-Generate an ArrayBuffer
formData ()-Generate formatted data that can be used for other requests
Other methods:
clone ()
Response.error ()
Response.redirect ()
response.headers
has (name) (boolean)-determine if the header exists
get (name) (String)-get the header data
getAll (name) (Array)-get all header data
set (name, value)-Set the parameters of the header
append (name, value)-add the contents of the header
delete (name)-delete header information
forEach (function (value, name) {...}, [thisContext])-loop through header information
Case
// Get the id attribute of ul in css
let uldom = document.getElementById ("students");
// Create a json file separately and get the address
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: $ {name}, age: $ {age} </ li>
`
}
uldom.innerHTML = html;
});
}
main ();
Combined with await final code
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();
The data.json file is as follows:
[
{"name":"z1","age":"3"},
{"name":"z2","age":"1"},
{"name":"z3","age":"4"},
{"name":"z4","age":"3"},
{"name":"z5","age":"5"}
]
The result after running is:
Name: z1, age: 3
Name: z2, age: 1
Name: z3, age: 4
Name: z4, age: 3
Name: z5, age: 5