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)!

如何用PHP和XML实现网站的分页和导航导言:在开发一个网站时,分页和导航功能是很常见的需求。本文将介绍如何使用PHP和XML来实现网站的分页和导航功能。我们会先讨论分页的实现,然后再介绍导航的实现。一、分页的实现准备工作在开始实现分页之前,需要准备一个XML文件,用来存储网站的内容。XML文件的结构如下:<articles><art

一、XML外部实体注入XML外部实体注入漏洞也就是我们常说的XXE漏洞。XML作为一种使用较为广泛的数据传输格式,很多应用程序都包含有处理xml数据的代码,默认情况下,许多过时的或配置不当的XML处理器都会对外部实体进行引用。如果攻击者可以上传XML文档或者在XML文档中添加恶意内容,通过易受攻击的代码、依赖项或集成,就能够攻击包含缺陷的XML处理器。XXE漏洞的出现和开发语言无关,只要是应用程序中对xml数据做了解析,而这些数据又受用户控制,那么应用程序都可能受到XXE攻击。本篇文章以java

当我们处理数据时经常会遇到将XML格式转换为JSON格式的需求。PHP有许多内置函数可以帮助我们执行这个操作。在本文中,我们将讨论将XML格式转换为JSON格式的不同方法。

Pythonxmltodict对xml的操作xmltodict是另一个简易的库,它致力于将XML变得像JSON.下面是一个简单的示例XML文件:elementsmoreelementselementaswell这是第三方包,在处理前先用pip来安装pipinstallxmltodict可以像下面这样访问里面的元素,属性及值:importxmltodictwithopen("test.xml")asfd:#将XML文件装载到dict里面doc=xmltodict.parse(f

使用nmap-converter将nmap扫描结果XML转化为XLS实战1、前言作为网络安全从业人员,有时候需要使用端口扫描利器nmap进行大批量端口扫描,但Nmap的输出结果为.nmap、.xml和.gnmap三种格式,还有夹杂很多不需要的信息,处理起来十分不方便,而将输出结果转换为Excel表格,方面处理后期输出。因此,有技术大牛分享了将nmap报告转换为XLS的Python脚本。2、nmap-converter1)项目地址:https://github.com/mrschyte/nmap-

xml中node和element的区别是:Element是元素,是一个小范围的定义,是数据的组成部分之一,必须是包含完整信息的结点才是元素;而Node是节点,是相对于TREE数据结构而言的,一个结点不一定是一个元素,一个元素一定是一个结点。

Scrapy是一款强大的Python爬虫框架,可以帮助我们快速、灵活地获取互联网上的数据。在实际爬取过程中,我们会经常遇到HTML、XML、JSON等各种数据格式。在这篇文章中,我们将介绍如何使用Scrapy分别爬取这三种数据格式的方法。一、爬取HTML数据创建Scrapy项目首先,我们需要创建一个Scrapy项目。打开命令行,输入以下命令:scrapys

1.在Python中XML文件的编码问题1.Python使用的xml.etree.ElementTree库只支持解析和生成标准的UTF-8格式的编码2.常见GBK或GB2312等中文编码的XML文件,用以在老旧系统中保证XML对中文字符的记录能力3.XML文件开头有标识头,标识头指定了程序处理XML时应该使用的编码4.要修改编码,不仅要修改文件整体的编码,还要将标识头中encoding部分的值修改2.处理PythonXML文件的思路1.读取&解码:使用二进制模式读取XML文件,将文件变为


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

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
