In jquery 1.5, a deferred object, JQ'sCodeIt also made a large-scale rewrite. If you want to know about this object, read: jquery deferred object detailed source code analysis (-)
JQ's Ajax method also adds new features to the deferred object. Now we use the new Ajax feature to implement xhr Proxy Cache. The main purpose is to avoid repeated requests.
Note: The proxy cache is mainly used to cache data pulled from the server. Do not use it when the client sends data to the server for processing.
There are two types of requests for the same URL
- Case 1: The first request has not been completed, and the second request has been sent;
- Case 2: The first request has been completed and the second request has been sent.
Therefore, we need to use two objects: _ xhrcache _ to save jqxhr and _ datacache _ to save the request results.
VaR Jqxhrcache = {_ Xhrcache __:{}, _ datacache __:{}, request: Function (OP, donecallback, failcallback ){ VaR Url =Typeof OP = 'string '? OP: op. url, enurl = Encodeuricomponent (URL), xca = This. _ xhrcache __, DCA = This. _ datacache __; If (! Xca [enurl]) {xca [enurl] = $. Ajax (OP). Done ( Function (Data) {DCA [enurl] = Data ;});} If (DCA [enurl] = Undefined ){
/* Scenario 1: append the callback event of the second request to the cached jqxhr object */xca [enurl]. Done (donecallback). Fail (failcallback );} Else {
/* Case 2: The callback event of the second request is executed using the cached result */donecallback. Call ( Null , DCA [enurl], xca [enurl]);} Return Xca [enurl] ;}};
The disadvantage of the above version is that _ xhrcache _ and _ datacache _ May be accidentally modified, although the name looks like a private member, but there is still the risk of being tampered with by the outside world, so the closure is used below to make them private.
VaR Jqxhrcache = (Function (){ VaR _ Xhrcache _ = {}, _ datacache _ = {}; Return {Request: Function (OP, donecallback, failcallback ){ VaR Url = Typeof OP = 'string '? OP: op. url, enurl = Encodeuricomponent (URL), xca =_ Xhrcache __, DCA = _ Datacache __; If (! Xca [enurl]) {xca [enurl] = $. Ajax (OP). Done ( Function (Data) {DCA [enurl] = Data ;});} If (DCA [enurl] = Undefined) {xca [enurl]. Done (donecallback). Fail (failcallback );} Else {Donecallback. Call ( Null , DCA [enurl], xca [enurl]);} Return Xca [enurl] ;};}) ();
The second request of the same URL can be avoided, but the cache object will be reset after the browser is refreshed or re-opened; if you need to save the request results for a long time (such as County and City data and other infrequently changed data), you can consider usingLocalstorage.
Usage:Jqxhrcache. Request ('/testdefer.html', function (data) {console. Log (data)}, function () {console. Log ('request fail ')});