简体   繁体   中英

jQuery caching JSON response

I am using a basic function to do AJAX requests and get a JSON:

function getData(endpoint) {
    return $.ajax({
        type: "GET",
        url: endpoint
    });
}

The problem is that sometimes the endpoint could be unresponsive or take too much time to load the data. In this case I would need to use the latest JSON that I got from the previous call to the endpoint.

I am looking for a way to keep track of the AJAX response time and if it exceeds a given limit of time to use the cached JSON response from the previous request.

Is there an elegant way to do it with jQuery?

Thanks for any suggestion

Trying to explain Anthony Gris comment with some sample code

var lastResponseData;

function getData(endpoint) {
   return $.ajax({
    type: "GET",
    url: endpoint,
    dataType: 'json',
    timeout: 1000,
    error:function(jqxhr, status){
    if(status==="error"){
      if(lastResponseData!=null){
       //use it
      }
    }
    else
    {
    getData(endpoint); try again
    },
    success:function(data){
     lastResponseData=data;
     //do work
    }

    }
 });
}

A variable and deferred objects + a timeout would make this easy:

var prevReq = $.Deferred().resolve().promise();

function getData(endpoint) {
    var newReq = $.ajax({
        type: "GET",
        url: endpoint,
        timeout: 2000
    }).then(function(data){
        // successful, set previous request to this request
        prevReq = newReq;
        return data;
    },function(){
        // it failed, return the previous successful request
        return prevReq;
    });
    return newReq;
}

getData("1").done(function(data){
    console.log(data);
})

http://jsfiddle.net/Tentonaxe/85HNs/2/

You should have functions to handle the diferent results of AJAX, but in the case of success you shoud store response in a global object, and in the always get data from there, like:

GlobalObj = {};
GlobalObj.response = {};

function getData(endpoint) {
    var data;
    $.ajax({
        type: "GET",
        url: endpoint
   })
   .done(function(){ 
   //store in global object
   })
   .fail(function(){})
   .always( function(){
        data = GlobalObj.response;
        //these methods are asyncronous 
        //here you should assing the value instead of returning
   });
}

You could save your last response in the browser cookies.

Take a look at jQuery cookie .

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