簡體   English   中英

如何在jQuery中緩存$ .post-request的結果?

[英]How to cache the result of $.post-request in jQuery?

我有一個小的jQuery腳本,通過查看ID來獲取信息。

什么是防止同一數據被請求多次的最佳方法(例如,jQuery中緩存的最佳實踐是什么)?

我試圖使用$.post$.ajax並將選項“cache”設置為true,但是請求被多次發送。

是否更好地保存收集的數據並使用集合來查看是否需要請求它?

歡迎任何想法和建議!

如果重要,我在服務器端使用ASP.Net MVC。

您在文檔中看到的cache選項是指瀏覽器的緩存。

您可以通過多種方式實現自記憶函數的模式,目標是確定參數的函數結果(在您的情況下為id )僅計算一次。

由於您使用的是Ajax請求,我建議您也使用回調參數,例如:

var getInfo = (function () {
  var cache = {}; // results will be cached in this object

  return function (id, callback) {
    if (cache[id] != null) { // if exist on cache
      callback(cache[id]);
      return;
    }
    // doesn't exists on cache, make Ajax request and cache it
    $.post("info.url", { "id": id }, function (data) { 
      cache[id] = data; // store the returned data
      callback(data);
    });
  };
})();

用法示例:

getInfo(5, function (data) {
  alert(data);
});

暫無
暫無

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

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