XMLHttpRequest(XHR)

介绍 (Introduction)

The introduction of XMLHttpRequest (XHR) in browsers in the mid 2000’s was a huge win for the Web Platform. Let’s see how it works.

在2000年代中期,浏览器中引入XMLHttpRequest(XHR)是Web平台的巨大胜利。 让我们看看它是如何工作的。

Things that now look normal, back in the day, looked like they were coming from the future. I’m talking about GMail or Google Maps, for example, which were all based in great part on XHR.

从现在开始,现在看起来很正常的事情看起来就像来自未来。 例如,我说的是GMail或Google Maps,它们都很大程度上基于XHR。

XHR was invented at Microsoft in the nineties, and became a de-facto standard as all browsers implemented it in the 2002-2006 period. The W3C standardized XMLHttpRequest in 2006.

XHR于90年代在Microsoft发明,并成为事实上的标准,因为所有浏览器均在2002-2006年间实施了XHR。 W3C在2006年对XMLHttpRequest进行了标准化。

As it sometimes can happen in the Web Platform, initially there were a few inconsistencies that made working with XHR quite different cross-browser.

由于它有时可能在Web平台中发生,因此最初存在一些不一致之处,使得使用XHR的跨浏览器大为不同。

Libraries like jQuery got a boost of popularity by providing an easy to use abstraction for developers, and this in turn helped spread the usage of this technology.

像jQuery这样的库通过为开发人员提供易于使用的抽象而得到了广泛的普及,这反过来又有助于推广该技术的使用。

XHR请求示例 (An example XHR request)

The following code creates an XMLHttpRequest (XHR) request object, and attaches a callback function that responds on the onreadystatechange event.

以下代码创建一个XMLHttpRequest(XHR)请求对象,并附加一个响应onreadystatechange事件的回调函数。

The xhr connection is set up to perform a GET request to https://yoursite.com, and it’s started with the send() method:

xhr连接被设置为执行对https://yoursite.com的GET请求,并以send()方法开始:

const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    xhr.status === 200 ? console.log(xhr.responseText) : console.error('error')
  }
}
xhr.open('GET', 'https://yoursite.com')
xhr.send()

其他open()参数 (Additional open() parameters)

In the example above we just passed the method and the URL to the request.

在上面的示例中,我们只是将方法和URL传递给了请求。

We can also specify the other HTTP methods - (get, post, head, put, delete, options).

我们还可以指定其他HTTP方法-( getpostheadputdeleteoptions )。

Other parameters let you specify a flag to make the request synchronous if set to false, and a set of credentials for HTTP authentication:

其他参数可让您指定一个标志(如果设置为false则使请求同步),以及一组用于HTTP身份验证的凭据:

open(method, url, asynchronous, username, password)

onreadystatechange (onreadystatechange)

The onreadystatechange is called multiple times during an XHR request. We explicitly ignore all the states other than readyState === 4, which means that the request is done.

在XHR请求期间,多次onreadystatechange 。 我们明确地忽略了readyState === 4以外的所有状态,这意味着请求已完成。

The states are

这些州是

  • 1 (OPENED): the request starts

    1(已打开):请求开始
  • 2 (HEADERS_RECEIVED): the HTTP headers have been received

    2(HEADERS_RECEIVED):已收到HTTP标头
  • 3 (LOADING): the response begins to download

    3(正在加载):响应开始下载
  • 4 (DONE): the response has been downloaded

    4(完成):响应已下载

中止XHR请求 (Aborting an XHR request)

An XHR request can be aborted by calling the abort() method on the xhr object.

可以通过在xhr对象上调用abort()方法来中止XHR请求。

与jQuery比较 (Comparison with jQuery)

With jQuery these lines can be translated to:

使用jQuery,这些行可以转换为:

$.get('https://yoursite.com', data => {
  console.log(data)
}).fail(err => {
  console.error(err)
})

与提取的比较 (Comparison with Fetch)

With the Fetch API this is the equivalent code:

使用Fetch API,这是等效的代码:

fetch('https://yoursite.com')
  .then(data => {
    console.log(data)
  })
  .catch(err => {
    console.error(err)
  })

跨域请求 (Cross Domain Requests)

Note that an XMLHttpRequest connection is subject to specific limits that are enforced for security reasons.

请注意,出于安全原因,XMLHttpRequest连接受特定限制的约束。

One of the most obvious is the enforcement of the same origin policy.

最明显的例子之一是执行相同来源策略。

You cannot access resources on another server, unless the server explicitly supports this using CORS (Cross Origin Resource Sharing).

您不能访问另一台服务器上的资源, 除非该服务器使用CORS(跨源资源共享)明确支持此资源

使用XHR上载文件 (Uploading files using XHR)

Check out my tutorial on how to upload files using XHR.

查看有关如何使用XHR上传文件的教程。

翻译自: https://flaviocopes.com/xhr/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值