簡體   English   中英

jQuery緩存JSON響應

[英]jQuery caching JSON response

我正在使用基本函數來執行AJAX請求並獲取JSON:

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

問題是有時終端可能沒有響應或者花費太多時間來加載數據。 在這種情況下,我需要使用從上一次調用端點獲得的最新JSON。

我正在尋找一種方法來跟蹤AJAX響應時間,如果它超過給定的時間限制,則使用上一個請求的緩存JSON響應。

使用jQuery有一種優雅的方式嗎?

謝謝你的任何建議

嘗試用一些示例代碼解釋Anthony Gris的評論

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
    }

    }
 });
}

變量和延遲對象+超時會使這很容易:

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/

您應該具有處理AJAX不同結果的函數,但是在成功的情況下,您應該在全局對象中存儲響應,並始終從那里獲取數據,例如:

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
   });
}

您可以將最后一個響應保存在瀏覽器cookie中。

看看jQuery cookie

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM