加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:10:55 所属栏目:百科 来源:网络整理
导读:我搜索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 tas
我搜索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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读