approach 发表于 2013-1-23 02:59:27

扩展$.post方法,增加浏览器端缓存功能

 
最近在做的一个东西,里面有需求需要在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;            // 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 && _postQueue.length>0 ){                  _postQueue.push(callback);                }                else                {                  _postQueue = ;                  $.post(url, data, function(data){                        _postCache = {birthday:now, data:data};                        var queue = _postQueue, 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.phpThe 0 times, and name is SupermanThe 1 times, and name is SupermanThe 2 times, and name is Superman 
可以看到,虽然调用了3次方法,但实际上只发出了一次请求(默认缓存时间是1s内)。
 
 
 
 
页: [1]
查看完整版本: 扩展$.post方法,增加浏览器端缓存功能