Keeping a jQuery .getJSON() connection open and waiting while in body of a page?

余生颓废 提交于 2019-12-04 17:00:13
cgp

Yeah, you're not going to want to use that loop, you're pretty much DOSing yourself not to mention locking the client.

Simple enough, create a polling plugin:

Source: http://web.archive.org/web/20081227121015/http://buntin.org:80/2008/sep/23/jquery-polling-plugin/

Usage:

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

The code to back it up:

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

Use a timeout, these types of loops are a really bad idea, so if you must employ polling for whatever reason, make sure you don't keep hammering your backend.

You either need to change to a polling method as described by altCognito, or you can use comet, which is designed to push data from the server to the client. Depending on your needs, you could use something like Jetty (for Java) or Twisted (Python) or WebSync (ASP.NET/IIS)

I think that this is about server push?

How about using the Socket.IO?

Ref: Introducing Socket IO 0.9, Google Group (http://socket.io/)

Ref: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery

Ref: Fun with websockets, Node.js and jQuery (http://nayna.org/blog/?p=159)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!