用Ajax和Dojo调查服务器 [英] Poll the Server with Ajax and Dojo

查看:98
本文介绍了用Ajax和Dojo调查服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 dojo.xhrPost 发送Ajax请求

这个调用被一个函数所包装的函数sendRequest()

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

每3秒)将相同的ajax发送到服务器

如何使用Dojo实现服务器轮询?我基本上需要调用 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);

这篇关于用Ajax和Dojo调查服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆