我正在使用 dojo.xhrPost发送 Ajax 请求
该调用由 function sendRequest()
我现在要连续(每 3 秒)向服务器发送相同的 ajax Post
如何使用 Dojo 实现服务器轮询?我基本上需要每 3 秒调用一次 sendRequest()
最佳答案
我不相信 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);
关于javascript - 使用 Ajax 和 Dojo 轮询服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2455900/