简体   繁体   English

如何在jQuery中缓存$ .post-request的结果?

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

I have a small jQuery script that gets information by looking at an ID. 我有一个小的jQuery脚本,通过查看ID来获取信息。

What is the best way to prevent that the same data are requested more than once (eg what's the best practices for caching in jQuery)? 什么是防止同一数据被请求多次的最佳方法(例如,jQuery中缓存的最佳实践是什么)?

I have tried to use $.post and $.ajax with option "cache" set to true, but the request is being sent more than once. 我试图使用$.post$.ajax并将选项“cache”设置为true,但是请求被多次发送。

Is it better to save collected data and use sets to see whether you'll have to request it or not? 是否更好地保存收集的数据并使用集合来查看是否需要请求它?

Any ideas and suggestions are welcome! 欢迎任何想法和建议!

If it matters, I use ASP.Net MVC on the server-side. 如果重要,我在服务器端使用ASP.Net MVC。

The cache option you saw on the documentation, refers to the browser's cache. 您在文档中看到的cache选项是指浏览器的缓存。

You can implement a pattern of self-memorizing functions in many ways, the goal is that the function result for determined argument ( id in your case) is only computed once. 您可以通过多种方式实现自记忆函数的模式,目标是确定参数的函数结果(在您的情况下为id )仅计算一次。

Since you are using an Ajax request, I would suggest you to use a callback argument also, eg: 由于您使用的是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);
    });
  };
})();

Example usage: 用法示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM