Cache AJAX requests

后端 未结 2 1370
别跟我提以往
别跟我提以往 2020-12-15 00:52

I am sending AJAX GET-requests to a PHP application and would like to cache the request returns for later use.

Since I am using GET this should be possible because d

2条回答
  •  忘掉有多难
    2020-12-15 01:44

    Once you refresh the page, you'll still be making server calls for content, even though you've requested them before. PHP headers won't help you out with that.

    I think what you need is a client-side caching mechanism of content already requested from the server in the current page.

    For this use-case you can use a hash table in JavaScript and query that before you make a call to the server. This will enhance user experience since the user won't have to wait for another request of content he's already seen.

    Here's an example:

    //placeholder for hash table as cache
    var cache = [];
    
    var getPage = function(pageNr){
        if(cache[pageNr]){
            //content is already in cache, use it from there
            handleContent(cache[pageNr]);
        }
        else{
            //object with parameteres sent with GET request
            var params = {};
            params.page = pageNr;
    
            $.ajax({
              url: "getHTML.php",
              data: params,
              cache: false,
              success: function(response){
                //handle your response here
                handleContent(response);
    
                //store the response in the cache for later use
                cache[pageNr] = response;
              }
            });
        }
    };
    

    Now requesting pages will first look in the current cache to see if you have the content. If not, it will make the server call and store the response in the cache.

    It is similar to the user-experience when scrolling through news in Google Finance

    NOTE that if you refresh the page this cache will be erased.

    In case of edits to a page you will have to use Maurice Perry's links to Yahoo Exceptional Performance in order to ensure that your server is always returning your latest version of content.

    More on hash tables in JavaScript: http://www.mojavelinux.com/articles/javascript_hashes.html

提交回复
热议问题