简体   繁体   中英

Caching AJAX query results with prototype

I'm looking at putting together a good way of caching results of AJAX queries so that the same user doesn't have to repeat the same query on the same page twice. I've put something together using a Hash which works fine but i'm not sure if there's a better method i could be using. This is a rough snippet of what i've come up with which should give you a general idea:

var ajaxresults;

document.observe("dom:loaded", function() {
    ajaxresults = new Hash();
    doAjaxQuery();
});

function doAjaxQuery(){
    var qs = '?mode=getSomething&id='+$('something').value;
    if(ajaxresults.get(qs)){
        var vals = (ajaxresults.get(qs)).evalJSON();
        doSomething(vals);
    }else{
        new Ajax.Request('/ajaxfile.php'+qs,{
            evalJSON: true,
            onSuccess: function(transport){
                var vals = transport.responseText.evalJSON();
                ajaxresults.set(qs,transport.responseText);
            },
            onComplete: function(){
                doSomething(vals);
            }
        });
    }
}

Did you try caching the AJAX requests by defining the cache content headers. Its another way and your browser will take care of caching. You dont have to create any hash inside your libraray to maintaing cache data.

High performance websites discussed lot about this. I dont know much about the PHP, but there is a way in .Net world to setting cache headers before writing the response to stream. I am sure there should be a similar way in PHP too.

If you start building a results tree with JSON you can check of a particular branch (or entry) exists in the tree. If it doesn't you can go fetch it from the server.

You can then serialize your JSON data and store it in window.name . Then you can persist the data from page to page as well.

Edit:

Here's a simple way to use JSON for this type of task:

var clientData = {}
clientData.dataset1 = [
    {name:'Dave', age:'41', userid:2345},
    {name:'Vera', age:'32', userid:9856}
]

if(clientData.dataset2) {
    alert("dataset 2 loaded")
}
else {
    alert("dataset 2 must be loaded from server")
}

if(clientData.dataset1) {
    alert(clientData.dataset1[0].name)
}
else {
    alert("dataset 1 must be loaded from server")
}

好吧,我想您可以对其进行更多抽象化(例如,通过cachedRequest()所有参数的组合以使其可在任何Ajax请求中普遍使用的cachedRequest()方法扩展Ajax ),但是一般方法对我来说看起来不错,我可以想不到更好/更快的解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM