[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()
}})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值