In web applications, JavaScript passes XMLHttpRequest (XHR) to perform asynchronous requests, which is a technology that effectively improves page communication. When we talk about Ajax technology, we usually mean Ajax based on XMLHttpRequest. Although Ajax is useful, but it's not the best API. It's not designed to adhere to the principle of separation of duties, mixing input, output, and state tracked with events into a single object. Moreover, event-based models are now JavaScript is at odds with its popular Promise and generator-based asynchronous programming models. What this article will introduce is the latest alternative technology to XMLHttpRequest—— Fetch API, which is an official standard from W3C.
Compatibility
Before introducing, let’s take a look at the current mainstream browser support for the Fetch API:
Fetch support It's still in the early stages, in Firefox 39 and above, and Chrome 42 All of the above are supported.
If you want to use it now, you can also use Fetch Polyfil to support those who do not yet support Fetch browser.
Before using Fetch, you can also perform functional testing on it:
if(self.fetch) { // run my fetch request here } else { // do something with XMLHttpRequest? }
Simple fetching example
In the Fetch API, the most commonly used function is the fetch() function. It receives a URL parameter and returns a promise to handle the response. response is a Response object:
fetch("/data.json").then(function(res) { // res instanceof Response == true. if (res.ok) { res.json().then(function(data) { console.log(data.entries); }); } else { console.log("Looks like the response wasn't perfect, got status", res.status); } }, function(e) { console.log("Fetch failed!", e); });
fetch() accepts a second optional parameter, an init object that can control different configurations. If submitting a POST request, the code is as follows:
fetch("http://www.example.org/submit.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "firstName=Nikhil&favColor=blue&password=easytoguess" }).then(function(res) { if (res.ok) { //res.ok用于检测请求是否成功 console.log("Perfect! Your settings are saved."); } else if (res.status == 401) { console.log("Oops! You are not authorized."); } }, function(e) { console.log("Error submitting form!"); });
If there is a network failure, the fetch() promise will reject, with a TypeError object. If you want to accurately determine whether fetch() is successful, you need to include the promise resolved situation, and then determine Response.ok at this time. is true.
Fetch implements four interfaces: GlobalFetch, Headers, Request and Response. GloabaFetch only contains one fetch method for obtaining network resources, and the other three directly correspond to the corresponding HTTP concepts. In addition, in In request/reponse, Body is also confused.
Headers
Headers interface allows defining HTTP The request headers (Request.headers) and response headers (Response.headers). A Headers object is a simple multi-name value pair:
var content = "Hello World"; var myHeaders = new Headers(); myHeaders.append("Content-Type", "text/plain"); myHeaders.append("Content-Length", content.length.toString()); myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
You can also pass a multi-dimensional array or object literal:
myHeaders = new Headers({ "Content-Type": "text/plain", "Content-Length": content.length.toString(), "X-Custom-Header": "ProcessThisImmediately", });
In addition, the Headers interface Provides set, delete and other APIs Used to retrieve its contents:
console.log(reqHeaders.has("Content-Type")); // true console.log(reqHeaders.has("Set-Cookie")); // false reqHeaders.set("Content-Type", "text/html"); reqHeaders.append("X-Custom-Header", "AnotherValue"); console.log(reqHeaders.get("Content-Length")); // 11 console.log(reqHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] reqHeaders.delete("X-Custom-Header"); console.log(reqHeaders.getAll("X-Custom-Header")); // []
Although some operations are only used in ServiceWorkers, they are relatively XHR itself provides a very convenient API for operating Headers.
For security reasons, some header fields can only be set through the User Agent Implementation, cannot be set programmatically: request header forbidden field and response header forbidden field.
If an illegal HTTP Header attribute name is used or an unwritable attribute is written, Headers Methods usually throw TypeError exceptions:
var myResponse = Response.error(); try { myResponse.headers.set("Origin", "http://mybank.com"); } catch(e) { console.log("Cannot pretend to be a bank!"); }
The best practice is to check whether the content type is correct before use, such as:
fetch(myRequest).then(function(response) { if(response.headers.get("content-type") === "application/json") { return response.json().then(function(json) { // process your JSON further }); } else { console.log("Oops, we haven't got JSON!"); } });
Since Headers can be sent in the request request or in the response Received in the request and specifying which parameters are writable, the Headers object has a special guard attribute. This property is not exposed to the web, but it affects what content can be Headers object is changed.
Possible values are as follows:
none: Default
r
equest:从 request 中获得的 headers(Request.headers)只读 request-no-cors:从不同域(Request.mode no-cors)的 request 中获得的 headers 只读 response:从 response 中获得的 headers(Response.headers)只读 immutable:在 ServiceWorkers 中最常用的,所有的 headers 都只读
Request
Request The interface defines the request format for requesting resources through HTTP. A simple request is constructed as follows:
var req = new Request("/index.html"); console.log(req.method); // "GET" console.log(req.url); // "http://example.com/index.html" console.log(req.headers); //请求头
Like fetch(), Request accepts a second optional parameter, an init that can control different configurations Object:
var myHeaders = new Headers(); var myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default' , credentials: true, body: "image data"}; var myRequest = new Request('flowers.jpg',myInit); fetch(myRequest,myInit) .then(function(response) { return response.blob(); }) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; });
#The mode attribute is used to determine whether cross-domain requests are allowed and which response attributes are readable. mode Optional attribute values:
same-origin: The request follows the same origin policy
no-cors: Default value, allowing scripts from CDN, images from other domains and other cross-domain resources (the Prerequisite is method can only be HEAD, GET or POST)
cors: cross-domain is allowed, the request follows the CROS protocol
credentials enumeration attribute determines whether cookies can be obtained across domains, which is consistent with XHR The withCredentials flag is the same, but has only three values, namely omit (default), same-origin and include.
Response
Response instance is processed by fentch() promises Instances of it that are later returned can also be created via JavaScript, but are only really useful within ServiceWorkers. When using respondWith() method and provides a custom response to accept the request:
var myBody = new Blob(); addEventListener('fetch', function(event) { event.respondWith(new Response(myBody, { headers: { "Content-Type" : "text/plain" } }); });
Response() constructor accepts two optional parameters—the response data body and an initialization object (and The init parameters accepted by Request() are similar.)
The most common response attributes are:
Response.status — 整数(默认值为200) 为response的状态码. Response.statusText — 字符串(默认值为OK),该值与HTTP状态码消息对应. Response.ok — 如上所示, 该属性是来检查response的状态是否在200-299(包括200,299)这个范围内.该属性返回一个Boolean值. Response.headers — 响应头 Response.type — 响应类型,如:basic/ cors /error
Body
Both Request and Response implement the Body interface. During the request process , both will carry Body, which can be an instance of any of the following types:
ArrayBuffer ArrayBufferView Blob/file URLSearchParams FormData
此外,Request 和 Response 都为他们的body提供了以下方法,这些方法都返回一个Promise对象:
arrayBuffer() blob() json() text() formData()
以上就是XML Http Request最新替代技术—— Fetch 的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!