javascript Ajax 同时多个请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7614042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax multiple requests at the same time
提问by themhz
recently I developed a project were I send multiple ajax requests at a single aspx page. I also put a timer were this request is happening with interval 5 seconds. Everything seems to work fine until suddenly the responses mix up. I know that I could do the same thing with one request, but I wonder why this is happening. I looked around the internet but I can't find any solution yet. I now actually adopted this style of coding like making one request with multiple results, but I wonder and I really want to know how to make multiple ajax request were the response will not mix up. This is my sample Code:
最近我开发了一个项目,我在单个 aspx 页面上发送多个 ajax 请求。我还设置了一个计时器,该请求以 5 秒的间隔发生。一切似乎都很好,直到突然反应混乱。我知道我可以用一个请求做同样的事情,但我想知道为什么会发生这种情况。我环顾了互联网,但还没有找到任何解决方案。我现在实际上采用了这种编码风格,例如发出一个具有多个结果的请求,但我想知道并且我真的很想知道如何发出多个 ajax 请求,否则响应不会混淆。这是我的示例代码:
$(document).ready(function () {
var a = setInterval("request1()", 5000);
var b = setInterval("request2()", 5000);
});
function request1() {
$.ajax({
url: 'ajaxhandler.aspx?method=method1' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
alert(data);
}
});
}
function request2() {
$.ajax({
url: 'ajaxhandler.aspx?method=method2' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
alert(data);
}
});
}
采纳答案by calvinf
If you need the requests to happen in order, you shouldn't be using AJAX (the first "a" is for "asynchronous").
如果您需要按顺序发生请求,则不应使用 AJAX(第一个“a”代表“异步”)。
To address this you can call request2() in the callback for the "success" of your first request.
为了解决这个问题,您可以在第一个请求的“成功”回调中调用 request2() 。
function request1() {
$.ajax({
url: 'ajaxhandler.aspx?method=method1' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
request2();
}
});
}
回答by Mohsen
This is not JavaScript fault, it's messed up because you are calling a single page in same time. If you had two server side page for your two AJAX files then it would be fine. Try to create two different aspx
file for you different methods
to have them called together.
这不是 JavaScript 错误,它搞砸了,因为您同时调用了单个页面。如果您的两个 AJAX 文件有两个服务器端页面,那就没问题了。尝试aspx
为您创建两个不同的文件,methods
以便将它们一起调用。
But that would not be a good practice. Why don't sent the method as an parameter and have a condition in your aspx
file for different methods? Then if you have two (or more) methods used at the same time, then simply send both to server with an single call. You will save a HTTP header and call delay for your call.
但这不是一个好的做法。为什么不将方法作为参数发送并在您的aspx
文件中为不同的方法设置条件?然后,如果您同时使用两种(或更多)方法,则只需通过一次调用即可将它们发送到服务器。您将为您的呼叫保存一个 HTTP 标头和呼叫延迟。
function requestAll() {
$.ajax({
url: 'ajaxhandler.aspx' ,
data: ['method1', 'method2'],
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
alert(data);
}
});
}
回答by Jon Newmuis
As has been stated, you cannot guarantee the order that the results return in. But if it is necessary to be able to determine this, you could conceivably create a unique identifier for each asynchronous request that is made, then sort out the incoming responses accordingly.
如前所述,您不能保证结果返回的顺序。但是如果有必要确定这一点,您可以为每个异步请求创建一个唯一标识符,然后相应地整理传入的响应.
An example where I see such a solution being useful is when performing actions on keystroke (e.g. onkeyup). When doing something like this, you may wish to encode a timestamp, version number, or similar, so that you can guarantee some sort of order. If the user is attempting to search "test", it is possible that the autocomplete response for "tes" would be returned before the response for "te". If you simply overwrite the autocomplete data, then this will obviously not be the desired behavior, as you could display incorrect results for the current search token(s).
我认为这种解决方案很有用的一个例子是对击键执行操作(例如 onkeyup)。执行此类操作时,您可能希望对时间戳、版本号或类似内容进行编码,以便保证某种顺序。如果用户尝试搜索“test”,则“tes”的自动完成响应可能会在“te”的响应之前返回。如果您只是覆盖自动完成数据,那么这显然不是您想要的行为,因为您可能会显示当前搜索标记的错误结果。
Encoding a timestamp (or unique ID, counter, version number, key, etc.) will allow you to check this to verify that you have the most up-to-date response, or sort the results by timestamp if you need to guarantee order, etc.
编码时间戳(或唯一 ID、计数器、版本号、密钥等)将允许您检查它以验证您是否拥有最新的响应,或者如果您需要保证订单,则按时间戳对结果进行排序, 等等。
回答by goertzenator
The function below will accept an array of urls for JSON requests, and invoke the callback with an array of results once all requests have completed. It can be easily adapted to non-JSON use.
下面的函数将接受 JSON 请求的 url 数组,并在所有请求完成后使用结果数组调用回调。它可以很容易地适应非 JSON 的使用。
The idea is to stash incoming responses into an array as they arrive, and then only invoke the callback once all results are in. This approach is a nice way to batch updates to the DOM and to avoid having a timer for each node you want to update.
这个想法是在传入的响应到达时将它们存储到一个数组中,然后只有在所有结果都输入后才调用回调。这种方法是批量更新 DOM 并避免为您想要的每个节点设置计时器的好方法更新。
function multi_getJSON(urls, callback)
{
// number of ajax requests to wait for
var count = urls.length;
// results of individual requests get stuffed here
var results = [];
// handle empty urls case
if(count === 0)
{
callback(results);
return;
}
urls.forEach(function(url, index)
{
$.getJSON(url, function(data)
{
results[index] = data;
count = count - 1;
// are we finished?
if(count === 0)
{
callback(results);
}
});
});
}