您的位置:首页 > 运维架构 > Linux

linux ethstatus命令

2010-08-05 15:02 369 查看
 

最近在做的一个东西,里面有需求需要在mouseover时间后,向服务端发送一次ajax请求。但最后发现某些浏览器,当鼠标即使停留在dom元素边上某个位置时,竟然连续不断的触发mouseover这个事件,于是干脆对ajax请求做了cache,在一定时间内的同一个url的相同参数的请求,使用以前缓存下来的数据,而不影响服务端。

 

扩展jQuery的$.post,实现ajax请求缓存的ajaxHelper的代码:

var ajaxHelper = function(){

var _postCache = {};
var _postQueue = {};

return {
post : function( url, data, callback, type, o ){
o = $.extend({
life : 1 // default is 1 second
}, o);
if ( $.isFunction( data ) ) {
type = callback;// fix the bug in $.post
callback = data;
data = {};
}
var key = '{0},{1},{2}'.format(url, type, $.param(data));
var now = +new Date;
var item = _postCache[key];
// the Javascript Date.getTime() return as millisecond.
if( item && now-item.birthday<o.life*1000 )
{
//					console.log('read from cache');
callback(item.data);
}
else
{
//					console.log('miss cache')
if( _postQueue[key] && _postQueue[key].length>0 ){
_postQueue[key].push(callback);
}
else
{
_postQueue[key] = [callback];
$.post(url, data, function(data){
_postCache[key] = {birthday:now, data:data};
var queue = _postQueue[key], f;
while( f=queue.shift() )
f(data);
}, type);
}
}
}
};
}();

 

测试代码:

$(function(){
$('#test').click(function(){
function test(i){
ajaxHelper.post('json.php', function(data){
console.log('The {0} times, and name is {1}'.format(i, data.name));
}, 'json');

}
for(var i=0;i<3;i++)
test(i);
});

})

HTML页面内容:

<div>

<input id="test" type="button" value="测试" />
</div>

 
测试结果:

 

POST http://approach.local/json.php The 0 times, and name is Superman
The 1 times, and name is Superman
The 2 times, and name is Superman

 

可以看到,虽然调用了3次方法,但实际上只发出了一次请求(默认缓存时间是1s内)。

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: