2010-03-16 73 views
3

我使用dojo.xhrPost來發送Ajax請求
的調用由function sendRequest()投票使用Ajax和Dojo服務器

包裹我現在已經持續(3秒鐘每次)發送相同的AJAX發送到服務器
如何使用Dojo實現服務器輪詢?基本上,我需要調用sendRequest()每3秒

回答

3

我不相信道場具有內置的輪詢方法,所以這裏有一個通用的方法,它是適用於整個構架

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.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); 
0

我發現它更好地做到這樣的:

  1. 有一個包含一個空的變量數組(隊列)
  2. setInterval在每次輪詢時將輪詢的新對象(使用輪詢參數)推送到數組(隊列)中;您也可以通過將具有相同參數的對象摺疊爲一個對象來壓縮民意調查;你甚至可以把處理函數放到這些對象中
  3. 有一個定時器來檢查隊列;如果沒有,返回
  4. 如果隊列中有掛起的對象,檢查是否已經存在尚未返回的掛起的xhr操作,只是等待 - 您不希望太多的xhr同時掛起,某些設備(例如新iPad)就可以了扼流圈
  5. 如果沒有未決XHR操作,出列第一調查對象和xhrGet它

這個程序的好處是,你可以很容易油門輪詢間隔,工作正常,當某些XHR操作超時,並且可以輕鬆實現投票請求的私有化。

0

要不斷更新網格,您可以將ajax請求包含在網格的「刷新完成」回調函數中。

yourGrid.on('dgrid-refresh-complete', function(event) { 

//Ajax request fireing every 3 sec 


}