Tom*_*Tom 4 javascript queue ajax
我有一个问题,主要是IE.
我需要能够一个接一个地处理n个查询.但是,如果我只是在for循环中调用我的函数,IE会做一些奇怪的事情(比如只加载这么多的调用).如果我使用一个警告框,它证明该功能可以获得所有的呼叫,并且令人惊讶的是IT工作!
我的猜测是IE需要比其他浏览器更多的时间,而警报框就是这样做的.
这是我的代码:
var Ajax = function(all) {
this.xhr = new XMLHTTPREQUEST(); // Function returns xhr object/ activeX
this.uri = function(queries) { // Takes an object and formats query string
var qs = "", i = 0, len = size(queries);
for (value in queries) {
qs += value + "=" + queries[value];
if (++i <= len) { qs += "&"; }
}
return qs;
};
xhr.onreadystatechange = function() { // called when content is ready
if (this.readyState === 4) {
if (this.status === 200) {
all.success(this.responseText, all.params);
}
this.abort();
}
};
this.post = function() { // POST
xhr.open("POST", all.where, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(uri(all.queries));
};
this.get = function() { // GET
xhr.open("GET", all.where + "?" + uri(all.queries), true);
xhr.send();
};
if (this instanceof Ajax) {
return this.Ajax;
} else {
return new Ajax(all);
}
};
Run Code Online (Sandbox Code Playgroud)
这个函数适用于单个请求,但是如何在循环中多次调用它时才能使它工作?
我认为这个问题可能与大多数Web浏览器实现的2个并发连接限制有关.
看起来您的Web服务响应的延迟使您的AJAX请求重叠,这反过来又超过了2个并发连接限制.
您可能想查看有关此限制的这些文章:
HTTP规范中也提出了这个限制:最后一段8.14节,这可能是大多数浏览器强加它的主要原因.
要解决此问题,您可能需要考虑仅在上一次AJAX调用成功响应后重新启动AJAX请求的选项.这样可以防止重叠发生.请考虑以下示例:
function autoUpdate () {
var ajaxConnection = new Ext.data.Connection();
ajaxConnection.request({
method: 'GET',
url: '/web-service/',
success: function (response) {
// Add your logic here for a successful AJAX response.
// ...
// ...
// Relaunch the autoUpdate() function in 100ms. (Could be less or more)
setTimeout(autoUpdate, 100);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个例子使用ExtJS,但你可以很容易地使用它XMLHttpRequest.
| 归档时间: |
|
| 查看次数: |
2981 次 |
| 最近记录: |