2013-10-30 49 views
-1

我試圖寫一個可以決定是否在localStorage的比不調用AJAX方法從服務器獲取數據,否則就應該調用AJAX API,並將結果存在靜態數據的代碼在localstorage中,並將數據返回給它的調用方法。調用jQuery的AJAX功能的localStorage

這裏是我的代碼:

staticService = function (key) { 
     return $.ajax({ 
      type: 'GET', 
      url: "xxxxx.ashx/" + key, 
      dataType: "json", 
      success: function(result){ 
       store.save(key, result); 
      } 
     }); 
    } 

var getFromStore = function (key) 
{ 
    if (key) { 
     var result = store.fetch(key); 
     if (!result) { 
      staticService(key);     
     } 
     return result; 
    } 
} 

var staticdata = { 
gender: [{value:"M",text:"Male"}, {value:"F",text:"Female"}], 
maritalStatus: getFromStore('availableMaritalStatus') 

};

問題:Ajax調用非同步,每當我經過那些不存儲密鑰它返回null,但它會在localStorage的Ajax調用和存儲數據。我需要somthing像

{ 
check list from store if exists return the list otherwise call ajax, get the list,  store it in localStorage and return to user but without blocking UI 
} 

我怎麼能通過改變我的代碼來實現這一點?最好的做法是什麼?

編輯:如何更改staticdata變量的邏輯,使我得到staticdata.maritalStatus一個有效的數據,而不是空。我正在加載應用程序負載的靜態數據。 如果我嘗試調用getFromStore的次數,我不知道我什麼時候會從服務器接收數據,因爲這將調用多次susccess回調。我希望靜態數據在所有靜態服務成功返回數據時被調用。

+0

的可能重複[?如何返回從AJAX調用的響應(http://stackoverflow.com/questions/14220321/how-to-return-the-response-from- an-ajax-call) –

+0

您需要傳遞一個回調函數,該函數可以在獲取關聯值時運行,而不是在函數結尾處使用返回值。然後可以使用已存儲的本地值調用回調,或者在完成時使用從ajax調用返回的值來調用回調。 – Archer

+0

但回調中的問題是我不知道我收到的迴應是哪個鍵。我必須一次性調用多個api服務。 –

回答

0

result爲null,因爲你不能從異步AJAX查詢返回的數據。 最好的方法是當查詢是'uccess'並在arg中傳遞返回值時執行回調函數。 這樣的:

staticService = function (key) { 
     return $.ajax({ 
      type: 'GET', 
      url: "xxxxx.ashx/" + key, 
      dataType: "json", 
      success: function(data) { 
       store.save(key, data); 
       callbackFunction(data); // Here you can call a callback function that will use your return value 
      } 
     }); 
} 
+0

我通過var staticdata = { 性別:[keyValue(「M」,「Male」,1),keyValue(「F」,「Female」)], 婚姻狀態:getFromStore ('availableMaritalStatus') };如何改變這一點?我在'staticdata.maritalStatus'@Archer中什麼都沒得到 –