重用 XMLHttpRequest 对象还是创建一个新对象?
我搜索了stackoverflow,但得到了矛盾的答案:
I searched stackoverflow but got contradictory answers:
为什么要重用 XmlHttpRequest 对象?
Ajax 密集型page:重复使用相同的 XMLHttpRequest 对象还是每次都创建一个新对象?
另外,w3schools.com 上也有推荐:
Also, there's a recommendation on w3schools.com :
如果您的网站上有多个 AJAX 任务,您应该创建一种用于创建 XMLHttpRequest 对象的标准函数,并调用这适用于每个 AJAX 任务.
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 任务.
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
推荐答案
你误解了 W3School 的建议.我将突出显示相关部分:
You misunderstood W3School's recommendation. I'll highlight the relevant part:
如果您的网站上有多个 AJAX 任务,您应该创建一个标准函数来创建 XMLHttpRequest 对象,并为每个 AJAX 任务调用它.
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
在符合标准的浏览器中,ActiveXObject
在 IE 中.
It says that you use one AJAX function to fetch requests. This function will deal with the inconsistencies between IE and other browsers. XMLHttpRequest
in standard-compliant browsers, and ActiveXObject
in IE.
我建议使用多个 XHR 对象.使用一个全局 xhr 对象,您的应用程序在给定时间只能处理一个请求.它也容易出错(例如,XMLHttpRequest 启动多次而不启动 onreadystatechange 函数).
I recommend to use multiple XHR objects. With one global xhr object, your application can only deal with one request at a given time. It's also error-prone (eg. XMLHttpRequest launches multiple times without initiating the onreadystatechange function).
W3schools 的意思是:
W3schools meant something like:
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代码>.
Although it's better to create a function which handles requests, such as jQuery.ajax
.
相关文章