编程语言
首页 > 编程语言> > javascript-使用Ajax和Dojo轮询服务器

javascript-使用Ajax和Dojo轮询服务器

作者:互联网

我正在使用dojo.xhrPost发送Ajax请求
该调用由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);

标签:ajax,polling,dojo,javascript
来源: https://codeday.me/bug/20191210/2099918.html