【问题标题】:Problem with long polling with JQuery on Tomcat Server在 Tomcat 服务器上使用 JQuery 进行长轮询的问题
【发布时间】:2010-08-31 13:37:58
【问题描述】:

我根据这个例子http://tomcat.apache.org/tomcat-7.0-doc/aio.html创建了一个CometServlet。然后我尝试使用 JQuery 从中获取数据。代码如下:

$(function() {

        $.longPoll = function(url, success, error) {
        $.ajax({
            url : url,
            success: function(data, status) {
                $.longPoll(url, success, error);
                if (success) {
                    success(data, status);
                }
            },
            error: function(data, status) {
                $.longPoll(url, success, error);
                if (error) {
                    error(data, status);
                }
            }
        });

    };

    $.longPoll("./comet", "", function(data, status) {
        alert("success:" + data);
    }, function(data, status) {
        alert("error:" + data);
    });
});

问题是成功函数没有触发(即使我可以在 FireBug 控制台中看到数据来了)。我认为这是因为服务器没有关闭响应编写器,但这是长轮询的目标:)

有人知道如何解决吗?

【问题讨论】:

    标签: jquery tomcat comet long-polling


    【解决方案1】:

    您需要覆盖xhr onreadystatechange 以便使用jQuery .ajax() 检查readyState === 3。示例:

    var xhr = $.ajax({});
    xhr._onreadystatechange = xhr.onreadystatechange;  // save original handler
    
    xhr.onreadystatechange = function() {
         xhr._onreadystatechange();         // execute original handler
         if (xhr.readyState === 3) alert('Interactive');
    };
    

    【讨论】:

    • 感谢您的回答!我添加了: beforeSend : function(xhr) { xhr._onreadystatechange = xhr.onreadystatechange; xhr.onreadystatechange = function() { if (xhr.readyState === 3) { alert(this.responseText); } 其他 { xhr._onreadystatechange(); } }; xhr.onprogress = xhr.onreadystatechange; } 到我的 $.ajax() 请求,但没有任何改变。抱歉,我无法格式化代码。
    【解决方案2】:

    问题的解决方案是添加计时器来检查长轮询流中的新数据。很好的解释在这里:http://www.bennadel.com/blog/1976-Long-Polling-Experiment-With-jQuery-And-ColdFusion.htm

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多