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

标签 javascript ajax dojo polling

我正在使用 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/

相关文章:

javascript - Django 设计模式 - 在加载时填充客户端 JavaScript 变量的方法

javascript - 将 json 对象从 ajax 存储到 javascript 2d 数组

javascript - dojo.addOnLoad() 永远不会在 GWT 页面中触发

javascript - 在 Angular 2 中对 html 表的列进行排序

javascript - 使用 Javascript 和 CSS 使波纹按钮可点击

javascript - 安全错误: Blocked a frame with origin from accessing a cross-origin frame

javascript - 使用 Dojo lang.hitch 将参数传递到被调用函数

javascript - 从 JS 中的 ids 自动创建变量?

JavaScript 与无 JavaScript 链接和表单

javascript - dijit.dialog 中的 TinyMCE 编辑器 : link dialog not working