ajax – 重用XMLHttpRequest对象还是创建一个新对象?

搜索stackoverflow但有矛盾的答案:

Why should I reuse XmlHttpRequest objects?

Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?

另外,有一个关于w3schools.com的建议:

If you have more than one AJAX task on your website,you should create
ONE standard function for creating the XMLHttpRequest object,and call
this for each AJAX task.

为什么这个建议?而是在我的页面上使用一个全局的XMLHttpRequest对象来处理所有的Ajax任务。

你误解了W3School的建议。我将突出相关部分:

If you have more than one AJAX task on your website,you should create ONE standard function for creating the XMLHttpRequest object,and call this for each AJAX task.

它表示您使用一个AJAX函数获取请求。此功能将处理IE和其他浏览器之间的不一致。符合标准的浏览器中的XMLHttpRequest,以及IE中的ActiveXObject。

我建议使用多个XHR对象。使用一个全局xhr对象,您的应用程序只能在给定时间处理一个请求。这也很容易出错(例如XMLHttpRequest launches multiple times without initiating the onreadystatechange function)。

W3schools的意思是:

function createXHR() {
    try {
        return new XMLHttpRequest();
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
}
var xhr = createXHR();
xhr.open('get','/test',true);
xhr.send();

虽然最好创建一个处理请求的函数,如jQuery.ajax

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...