【问题标题】:Poll the Server with Ajax and Dojo使用 Ajax 和 Dojo 轮询服务器
【发布时间】:2010-03-16 15:54:40
【问题描述】:

我正在使用 dojo.xhrPost 发送 Ajax 请求
调用由function sendRequest() 包裹

我现在必须连续(每 3 秒)将相同的 ajax Post 发送到服务器
如何使用 Dojo 实现服务器轮询?我基本上需要每 3 秒拨打一次sendRequest()

【问题讨论】:

    标签: javascript ajax dojo polling


    【解决方案1】:

    我不相信 Dojo 有内置的轮询方法,所以这里有一个适用于跨框架的通用方法

    var Poll = function(pollFunction, intervalTime) {
        var intervalId = null;
    
        this.start = function(newPollFunction, newIntervalTime) {
            pollFunction = newPollFunction || pollFunction;
            intervalTime = newIntervalTime || intervalTime;
    
            if ( intervalId ) {
                this.stop();
            }
    
            intervalId = setInterval(pollFunction, intervalTime);
        };
    
        this.stop = function() {
            clearInterval(intervalId);
        };
    };
    

    用法:

    var p = new Poll(function() { console.log("hi!"); }, 1000);
    p.start();
    setTimeout(function() { p.stop();}, 5000);
    

    或者在你的情况下:

    var p = new Poll(sendRequest, 3000);
    p.start();
    

    如果你想把它作为一个 Dojo 包,那么下面是一个简单的扩展:

    dojo.provide("Poll");
    
    dojo.declare("Poll", null, {
        intervalId:   null,
        pollFunction: null,
        intervalTime: null,
    
        constructor: function(newPollFunction, newIntervalTime) {
            this.pollFunction = newPollFunction;
            this.intervalTime = newIntervalTime;
        },
    
        start: function(newPollFunction, newIntervalTime) {
            this.pollFunction = newPollFunction || this.pollFunction;
            this.intervalTime = newIntervalTime || this.intervalTime;
    
            this.stop();
            this.intervalId = setInterval(this.pollFunction, this.intervalTime);
        },
    
        stop: function() {
            clearInterval(this.intervalId);
        }
    });
    

    用法:

    var p = new Poll(function() {console.log("hi");}, 250);
    p.start();
    setTimeout(dojo.hitch(p, p.stop), 1000);
    

    【讨论】:

      【解决方案2】:

      我发现这样做更好:

      1. 有一个包含空数组(队列)的变量
      2. setInterval 进行轮询,在每次轮询时,将一个新对象(带有轮询参数)推送到数组(队列)中;您还可以通过将具有相同参数的对象折叠到一个对象中来压缩民意调查;您甚至可以将处理函数放入这些对象中
      3. 有一个计时器来检查队列;如果没有,则返回
      4. 如果队列中有待处理的对象,检查是否已经存在未返回的待处理 xhr 操作,只需等待 - 您不希望同时有太多 xhr 待处理,某些设备(例如 iPad)会阻塞它
      5. 如果没有挂起的 xhr 操作,则将第一个轮询对象出列并 xhr 获取它

      此过程的好处是您可以轻松限制轮询间隔,在某些 xhr 操作超时时可以正常工作,并且可以轻松实现轮询请求的私有化。

      【讨论】:

        【解决方案3】:

        要不断更新您的网格,您可以将您的 ajax 请求包含在网格的“刷新完成”回调函数中。

        yourGrid.on('dgrid-refresh-complete', function(event) { 
        
        //Ajax request fireing every 3 sec
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 2012-04-15
          • 2015-04-06
          • 1970-01-01
          • 2012-11-28
          • 1970-01-01
          • 2019-02-10
          • 1970-01-01
          • 2021-12-29
          • 2013-05-25
          相关资源
          最近更新 更多