保持jQuery .getJSON()连接打开并在页面正文中等待?

Van*_*yen 2 javascript jquery comet server-push

我正在编写一个基本的推送消息系统.一个小小的改变导致它正常停止工作.让我解释.在我的原始版本中,我能够将代码放在文档中,如下所示:

<head>
  ...text/javascript">
  $(document).ready(function(){
    $(document).ajaxStop(check4Updates);
    check4Updates();
  });

  function check4Updates(){
    $.getJSON('%PATH%', callback);
  };
...
</head>
Run Code Online (Sandbox Code Playgroud)

这很好地工作,即使服务器返回null(它会在超时2分钟之后),也会保持连接打开.它会无限期地一遍又一遍地调用getJSON函数.快乐的熊猫.

现在,我必须将代码段放在标签之间.几乎无法访问$(document).ready()函数.

<body>
...
check4Updates();
$("body").ajaxStop(check4Updates);
...
</body>
Run Code Online (Sandbox Code Playgroud)

这有效......一段时间.此后不久,它将停止调用check4Updates并进入无限循环并使用100%处理器时间.

我试图得到它,以便重复调用check4Updates直到页面关闭.如果有人对我为什么简单的更改不再按预期运行有任何见解,请告诉我.感谢您抽出宝贵时间阅读并帮助我.

最诚挚的问候,Van Nguyen

cgp*_*cgp 6

是的,你不会想要使用那个循环,你几乎在考虑自己,更不用说锁定客户端了.

很简单,创建一个轮询插件:

资料来源:http://web.archive.org/web/20081227121015/http : //buntin.org : 80/2008/ sep/23/ jquery-polling-plugin/

用法:

$("#chat").poll({
    url: "/chat/ajax/1/messages/",
    interval: 3000,
    type: "GET",
    success: function(data){
        $("#chat").append(data);
    }
});
Run Code Online (Sandbox Code Playgroud)

备份代码:

(function($) {
    $.fn.poll = function(options){
        var $this = $(this);
        // extend our default options with those provided
        var opts = $.extend({}, $.fn.poll.defaults, options);
        setInterval(update, opts.interval);

        // method used to update element html
        function update(){
            $.ajax({
                type: opts.type,
                url: opts.url,
                success: opts.success
            });
        };
    };

    // default options
    $.fn.poll.defaults = {
        type: "POST",
        url: ".",
        success: '',
        interval: 2000
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

  • 是的,或几乎听起来像他想要彗星.http://plugins.jquery.com/project/Comet (2认同)