問題描述
我搜索了stackoverflow,但得到了矛盾的答案:
I searched stackoverflow but got contradictory answers:
為什么要重用 XmlHttpRequest 對象?
Ajax 密集型page:重復(fù)使用相同的 XMLHttpRequest 對象還是每次都創(chuàng)建一個新對象?
另外,w3schools.com 上也有推薦:
Also, there's a recommendation on w3schools.com :
如果您的網(wǎng)站上有多個 AJAX 任務(wù),您應(yīng)該創(chuàng)建一種用于創(chuàng)建 XMLHttpRequest 對象的標準函數(shù),并調(diào)用這適用于每個 AJAX 任務(wù).
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 任務(wù).
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
推薦答案
你誤解了 W3School 的建議.我將突出顯示相關(guān)部分:
You misunderstood W3School's recommendation. I'll highlight the relevant part:
如果您的網(wǎng)站上有多個 AJAX 任務(wù),您應(yīng)該創(chuàng)建一個標準函數(shù)來創(chuàng)建 XMLHttpRequest 對象,并為每個 AJAX 任務(wù)調(diào)用它.
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 函數(shù)來獲取請求.這個函數(shù)會處理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 對象,您的應(yīng)用程序在給定時間只能處理一個請求.它也容易出錯(例如,XMLHttpRequest 啟動多次而不啟動 onreadystatechange 函數(shù)).
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();
雖然最好創(chuàng)建一個處理請求的函數(shù),例如 jQuery.ajax代碼>.
Although it's better to create a function which handles requests, such as jQuery.ajax
.
這篇關(guān)于重用 XMLHttpRequest 對象還是創(chuàng)建一個新對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!