【问题标题】:Jquery Queued request with timeJquery排队请求与时间
【发布时间】:2014-05-21 16:21:11
【问题描述】:

我有一个用于向论坛用户发送消息的表单。这些消息每 35 秒发送一次(安全策略论坛),带有 jQ​​uery $.ajax 发布请求...

我在input和textarea中把消息的名称和文本对应起来。我想做的方法:

单击“发送”按钮,使用用户和文本请求论坛消息。

双击“发送”按钮,使用用户和文本请求论坛消息。

3-单击“发送”按钮,使用用户和文本请求论坛消息。

4-单击“发送”按钮,使用用户和文本请求论坛消息。

5-......

这四个或更多请求同时在队列中。但是,

我需要运行第一个请求并等待 35 秒

运行第二个请求后等待 35 秒

运行 tirth 请求后等待 35 秒

运行第四个请求后等待 35 秒

....

对不起,我的英语不好。

感谢回复

【问题讨论】:

  • 您可以维护一个数组,该数组在每次单击时刷新并推送到数组中,并且在处理下一个请求并移出数组时每 35 分钟刷新一次。
  • 我该怎么做?请;)
  • 向我们展示一些示例 HTML(按钮)和您的代码 (JS)。
  • 我什么都没做。只需在 x 秒内指向并加载和卸载数据数组。谢谢;)
  • 请参阅下面我的回答中的逻辑。 逻辑应该让你知道该怎么做。

标签: jquery ajax queue


【解决方案1】:

在没有任何代码可以使用的情况下,这是我的建议。您将创建并维护一个数组,其中包含发出将发送消息的 ajax 调用所需的所有相关信息。

每次进行符合条件的点击时,数组都会更新一个附加项目。第一次单击(当数组为空时进行的任何单击)从计数器开始。一旦数组中的每个请求(第一个元素),使用.shift() 方法从数组中删除该元素。如果数组为空,则停止计数器。

$(function() {
    var requests = [],
        sender,
        url = 'url-to-send-ajax-call-to';

    //Have as many of these as the number of different buttons the user may click
    $('button').on('click', scheduleRequest);

    function scheduleRequest() {
        //in here 'this' references the button that was clicked
        //if it contains data, use it.
        requests.push({
            something:$(this).data('something')/*data from button*/,
            email:'ab@c.com',
            message:'whatever other parameters you want to send'
        });

        //if setInterval is not running
        if( !sender ) {
            //fire it up and store a reference to it
            sender = setInterval(sendRequest, 35000);
        }
    }

    function sendRequest() {
        $.post( url, requests[ 0 ], function( data ) {
            requests.shift(); // remove request just processed
            //if no more requests        
            if( requests.length === 0 ) {
                //stop setInterval
                clearInterval( sender );
                sender = undefined;
            }
        }).fail(function() {
            // Do something if call fails
        });
    }
});

类似的东西。希望这能让您对如何进行有所了解。

JS FIDDLE DEMO

【讨论】:

  • 哇!!它对我来说是完美的,而且效果很好!!感谢感谢感谢感谢感谢感谢感谢感谢感谢;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 2011-06-16
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多