XMLHttpRequest to complete Ajax is a bit old and outdated.
Fetch () enables us to perform AJAX functions similar to those provided by XMLHttpRequest (XHR). The main difference between them is that the Fetch API uses promises, which makes the interface simpler and simpler, avoids the complexity of the callback, and eliminates the use of complex XMLHttpRequest APIs.
If you have not used promises before, you should first look at the article "JavaScript promises usage."
First, basic fetch usage
Let's use an example to compare the difference between using XMLHttpRequest and using the fetch. We want to request a URL to get the return result in JSON format.
XMLHttpRequest
A XMLHttpRequest request requires two listeners to capture the success and error two scenarios, and the open () and send () methods need to be invoked.
function Reqlistener () {
var data = Json.parse (This.responsetext);
Console.log (data);
}
function Reqerror (err) {
console.log (' Fetch Error:-S ', err);
}
var oreq = new XMLHttpRequest ();
Oreq.onload = Reqlistener;
Oreq.onerror = Reqerror;
Oreq.open (' Get ', './api/some.json ', true);
Oreq.send ();
Fetch
The code for our fetch request is basically this:
Fetch ('./api/some.json ')
. Then (
function (response) {
if (Response.Status!==) {
Console.log (' Looks like there is a problem. Status Code: ' +
response.status ';
return;
}
Examine the text in the response
Response.json (). Then (function (data) {
console.log (data);}
);
)
. catch (function (err) {
console.log (' Fetch Error:-S ', err);
});
We first check that the status of the request response is 200 before parsing the response data according to the JSON object.
The fetch () request gets the content that is a Stream object. That is, when we call the JSON () method, the return is still a Promise object, because the stream is read asynchronously.
Returns the metadata for a data object (Metadata)
In the example above, I see the basic state of the server Response object response and how to convert to JSON. The corresponding object returned has a lot of metadata information in the response, and here are some of the following:
Fetch (' Users.json '). Then (function (response) {
Console.log (response.headers.get (' Content-type '));
Console.log (Response.headers.get (' Date '));
Console.log (response.status);
Console.log (response.statustext);
Console.log (response.type);
Console.log (Response.url);
});
Object response type of response
When we execute a FETCH request, the type of the response's data Response.type can be "basic", "cors" or "opaque". These types are used to explain how the data and data should be treated.
When a request originates from the same domain, the response type will be "basic", and there will be no restrictions on the use of the response content.
If the request is from a different domain and the response has Cors header information, then the response type will be "cors". The "Cors" and "basic" types of responses are basically the same, except that the "cors" type of response limits the header information you can only see includes ' Cache-control ', ' content-language ', ' content-type ', ' Expires ', ' last-modified ', and ' Pragma '.
The "opaque" type of response indicates that the request came from another domain and does not have CORS header information. A response of a opaque type will not be read and cannot be read to the requested State to see whether the request was successful or not. The current fetch () implementation cannot execute such a request.
You can specify a pattern for the fetch request, which requires it to execute only the specified pattern of requests. This pattern can be divided into:
"Same-origin" only requests from the same domain to be successful, others will be rejected.
"Cors" allows requests from different domains, but requires the correct cors header information.
"Cors-with-forced-preflight" executes preflight check before performing a real call.
This mode of "No-cors" is currently not enforceable.
The way to define a pattern is to use a Parameter object as the second parameter of the Fetch method:
Fetch (' Http://some-site.com/cors-enabled/some.json ', {mode: ' Cors '})
. Then (function (response) {
return Response.text ();
})
. Then (function (text) {
Console.log (' Request successful ', text;
})
. catch (function (error) {
log (' Request failed ', error)
});
Tandem promises
One of the biggest features of promises is that you can concatenate various operations. For the fetch, we can share some logical operations in each fetch operation.
When using the JSON API, we need to check the status of each request response and then parse it into a JSON object. With promise, we can simply put the parsing state and parse JSON code into a separate function, and then return as promise, so that the code is more organized.
function status (response) {
if (response.status >= && Response.Status <) {return
PROMISE.R Esolve (response)
} else {return
promise.reject (new Error (Response.statustext)
}
}
function JSON (response) {return
Response.json ()
}
fetch (' Users.json ')
. Then (status)
. Then (JSON)
. Then (function (data) {
Console.log (' Request succeeded with JSON response ', data;
}). catch (function (error) {
Console.log (' Request failed ', error);
});
We use the status function to check response.status and return the result of Promise.resolve () or Promise.reject (), which is also a Promise. In our fetch () call chain, first if the fetch () execution result is resolve, then the JSON () method is called, and the method returns a Promise so we get an parsed JSON object. If the analysis fails, the Reject function and the catch statement are executed.
You will find that in the fetch request we can share some business logic that makes the code easier to maintain, more readable, and more testable.
Perform form data submission with fetch
In Web applications, submitting a form is a very common operation, and submitting form data with a fetch is also very concise.
The method and body parameter options are provided in the fetch.
Fetch (URL, {method
: ' Post ',
headers: {"
content-type": "application/x-www-form-urlencoded; Charset=utf-8 "
}, Body
: ' Foo=bar&lorem=ipsum '
})
. Then (JSON)
. Then (function (data) {
Console.log (' Request succeeded with JSON response ', data);
catch (function (error) {
Console.log (' Request failed ', error);
});
Send user credential information in a FETCH request
If you want to include voucher information such as cookies in the fetch request, you can set the credentials parameter to the "include" value.
Fetch (URL, {
credentials: ' Include '
})
Obviously, the fetch API is much simpler than the traditional XMLHttpRequest (XHR), which is no less than the Ajax API provided in jquery.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.