How to cache the result of a $ .post query in jQuery?

I have a small jQuery script that gets information by looking at the identifier.

What is the best way to prevent reuse of the same data (e.g. what are the guidelines for caching in jQuery)?

I tried to use $.postand $.ajaxwith the parameter "cache", set to true, but the request is sent more than once.

Is it better to save the collected data and use the sets to see if you need to request them or not?

Any ideas and suggestions are welcome!

If that matters, I use ASP.Net MVC on the server side.

+3
source share
1 answer

The option cachethat you saw in the documentation relates to the browser cache.

You can implement the self-starting function template in many ways, the goal is that the function result for a specific argument ( idin your case) is calculated only once.

Since you are using an Ajax request, I would suggest you use a callback argument, for example:

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

Usage example:

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

Source: https://habr.com/ru/post/1727154/


All Articles