`
全冠清
  • 浏览: 51666 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

[jquery plugin]http轮询

阅读更多
/**
 * @author 全冠清
 */
(function($){

    var methods = {
        init: function(opts){
			 if(!$(window).data('register_messageline')){
			 	$(window).data('register_messageline',true)
			 }else{
			 	alert('error:只允许有一个请求总线')
				return;
			 }
			 var defaults = {
			 	actions:[],
				timeout: 80000//默认ajax请求超时时间80秒  
			 }
            var setting = $.extend(true, defaults, opts)
			if(!$(window).data('messageline')){
				  $(window).data('messageline',[])
			}
			$.each(setting.actions,function(i,item){
				$(window).data('messageline').push(item)
			})
            function messageline(){
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: setting.url,
                    timeout: setting.timeout, 
                    data:setting.data, 
                    success: function(messages, textStatus){
                        //从服务器得到数据,显示数据并继续查询  
                         $.each(messages,function(i,item){
						 	$.each($(window).data('messageline'),function(j,active){
								if(active.name===item.name){
									active.action(item.data)
								}
							})
						 })
						messageline()
                    },
                    //Ajax请求超时,继续查询  
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        if (textStatus == "timeout") {
                           messageline()
                        }
                    }
                });
            }
			messageline()
        },
        addlistener: function(active){
            if(!$(window).data('messageline')){
				  $(window).data('messageline',[])
			}
			$(window).data('messageline').push(active)
        }
    };
    
    $.comet = function(method){
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else 
            if (typeof method === 'object' || !method) {
                return methods.init.apply(this, arguments);
            }
            else {
                $.error('Method ' + method + ' does not exist on jQuery.comet');
            }
    };
    
})(jQuery);
 


用法
//初始化(仅需要一次)
$.comet({
		url:'url'
	})

//使用(可任意多种消息类型)
$.comet('addlistener',{name:'newMessage(请求的名字)',action:function(data){
		//$('.new_state').html('有'+data+'条新动态,赶快点击查看哦!').show()
	}})
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics