轮询使用Ajax和Dojo的服务器服务器、Ajax、Dojo

2023-09-10 17:45:04 作者:東城,依舊。

我使用 dojo.xhrPost 以发送Ajax的请求 电话被包裹在函数sendRequest将()

I'm using dojo.xhrPost to sent Ajax Requests The call is wrapped by a function sendRequest()

我现在已经连续(每3秒)发送相同的AJAX发布到服务器 我怎样才能实现与道场服务器轮询?基本上,我需要调用 sendRequest将()每3秒

I've now to continuously (every 3sec) send the same ajax Post to the server How can I implement a Server Poll with Dojo? I basically need to call sendRequest() every 3 secs

推荐答案

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

I don't believe that Dojo has a method built-in for polling, so here's a generic method that's applicable across frameworks

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包,再下面是一个简单的扩展:

If you want this as a Dojo package, then the following is a trivial extension:

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