简体   繁体   English

同时Ajax多个请求

[英]Ajax multiple requests at the same time

recently I developed a project were I send multiple ajax requests at a single aspx page. 最近我开发了一个项目,我在一个aspx页面上发送了多个ajax请求。 I also put a timer were this request is happening with interval 5 seconds. 我还放了一个计时器,这个请求发生间隔5秒。 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. 我现在实际上采用了这种编码风格,比如使用多个结果发出一个请求,但我想知道并且我真的想知道如何制作多个ajax请求,响应不会混淆。 This is my sample Code: 这是我的示例代码:

 $(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);
            }

        });
    }

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();
        }

    });
}

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. 下面的函数将接受JSON请求的URL数组,并在完成所有请求后使用一组结果调用回调。 It can be easily adapted to non-JSON use. 它可以很容易地适应非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);
            }
        });
    });
}

This is not JavaScript fault, it's messed up because you are calling a single page in same time. 这不是JavaScript的错误,因为你在同一时间调用单个页面而搞砸了。 If you had two server side page for your two AJAX files then it would be fine. 如果您的两个AJAX文件有两个服务器端页面,那就没关系了。 Try to create two different aspx file for you different methods to have them called together. 尝试创建两个不同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? 为什么不将方法作为参数发送并在aspx文件中为不同的方法设置条件? 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. 您将为呼叫保存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);
            }

        });
    }

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 (eg onkeyup). 我看到这样的解决方案有用的一个例子是在击键时执行动作(例如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". 如果用户试图搜索“test”,则可能在“te”的响应之前返回“tes”的自动完成响应。 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). 如果您只是覆盖自动填充数据,那么这显然不是所需的行为,因为您可能会显示当前搜索令牌的错误结果。

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,计数器,版本号,密钥等)进行编码将允许您检查此项以验证您是否拥有最新响应,或者如果您需要保证订单,则按时间戳对结果进行排序等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM