现在的位置: 首页 > 综合 > 正文

JQuery实时网站在线人数显示

2018年04月03日 ⁄ 综合 ⁄ 共 587字 ⁄ 字号 评论关闭

使用的ajax长轮询 ajax long poll,为了便于使用,将它封装成一个jquery插件

(function($){
    $.fn.extend({
        visitors: function(options){
            var defaults = {
                script : "visitors/online.php",
                timeout : 50000,
            };
            var options = $.extend(defaults, options);
            return this.each(function(){
                var holder = $(this);
                refresh = function(sleep) {
                    var sleep = sleep ? sleep : 1000;
                    setTimeout('update()', sleep);
                }
                update = function() {
                    $.ajax({
                        url : options.script,
                        type : 'get',
                        dataType : 'json',
                        async : true,
                        cache : false,
                        timeout : options.timeout,
                        beforeSend : function() {
                        },
                        success : function(data) {
                            holder.html(data.num);
                            refresh(1000);
                        },
                        error : function() {
                            refresh(15000);
                        }
                    });
                }
                update();
            });
        }
    });
})(jQuery);

抱歉!评论已关闭.