XML Http Request latest alternative technology - Fetch
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中文网(www.php.cn)!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and
