简体   繁体   English

避免第二次 ajax 调用的好方法

[英]Good way of avoiding a second ajax call

So I'm doing a an ajax call in this function somewhat like this:所以我在这个 function 中做一个 ajax 调用,有点像这样:

function getCount() {
  $.get("/People/getCount", function (data) {
    if (data && data != "") { 
      // lots of code in here
      }

What I'm doing in another function is making a second call like this:我在另一个 function 中所做的第二次调用是这样的:

function worldPeople() {
    return $.get("/People/getCount", function (data) {
     if (data != 0) {
        var target = $("#worldNumbers").find("span");
        target.html(data.length).digits();

     }
  })
}

So I really would like to avoid making that second call.所以我真的很想避免打第二个电话。 Is there any good way in avoiding that?有什么好的方法可以避免吗? Maybe do some chaining or such, reusing the callback from the first one?也许做一些链接等,重用第一个回调? I've heard that its bad practice to do several calls.我听说打几个电话是不好的做法。 Regards问候

Would like to thank all who answered.想感谢所有回答的人。 In the end did not use any of the solutions, I solved it in another way.最后没有使用任何解决方案,我用另一种方式解决了它。 I'm sure most of the examples you gave me were really good.我相信你给我的大多数例子都非常好。 Do not know how to do with accepting answers.不知道如何接受答案。 Accept all or none?!全部接受还是不接受?! Thanks!谢谢!

You could create a simple data store:您可以创建一个简单的数据存储:

App.store = function () {
    this.people = null;
    this.count
    loadPeople = function () {
         if(this.people === null) {
          $.get("/People/getCount", function (data) {
          if (data != 0) {
               this.count = (data.length).digits();
               this.people = data;
           }
         }
    };
} 

Well, you can just send the function pointer to the function that executes $.get好吧,您可以将 function 指针发送到执行 $.get 的 function

basically you would then do this:基本上你会这样做:

function worldPeople() {
    getCountFromServer(function(data){
        //do sth with data
    });
}

function getCount() {
    getCountFromServer(function(data){
          //do sth with data
    });
}

function getCountFromServer(callback) {
    return $.get("/People/getCount", function (data) {
        if (data)
            callback(data);
    });
}

What about store count of peoples in hidden field?隐藏区域的商店人数呢? And than check this field before sending request.而不是在发送请求之前检查此字段。

You can achieve this by handling your Ajax requests using some sort of cache.您可以通过使用某种缓存处理 Ajax 请求来实现此目的。 I use a cache that saves the information retrieved based on the url it called.我使用一个缓存来保存根据它调用的 url 检索到的信息。 If another function sets off the same request the cache returns the alraedy fetched data.如果另一个 function 发出相同的请求,缓存将返回已获取的数据。

What you do need to do as well though is check if the data is outdated so you can refetch it if necessary.您还需要做的是检查数据是否已过时,以便在必要时重新获取它。

I generally use a caching module pattern for this kind of thing:我通常对这种事情使用缓存模块模式:

// create a quick singleton to store cached data
var People = (function() {
    // private variable to act as cache
    var count;

    // function to get cached data
    // note: You have to assume it's always asynchronous
    function getCount(callback) {
        // have we loaded the data yet?
        if (count===undefined) {
            // cache miss: load the data, store it, do the callback
            $.get("/People/getCount", function (data) {
                count = data;
                callback(data);
            }
        } else {
            // cache hit - no need to reload
            callback(count);
        }
    }

    // provide access to the getter function
    return {
        getCount: getCount
    };

}());

The first time you hit the cache, it'll load from the server;第一次访问缓存时,它会从服务器加载; the second time it will load from the private variable.第二次它将从私有变量加载。

// will load the data asynchronously
People.getCount(function(count) {
    alert("First hit: " + count);
});

// will use the cached data
People.getCount(function(count) {
    alert("Second hit: " + count);
});

Depending on the complexity you want to support, you could add additional features like expiring the cache after a particular interval, caching multiple calls (potentially keyed to the AJAX URL), etc. I like to keep the API simple and not reference the AJAX URLs - that way your cache acts like an abstracted service layer, and you can create other cache implementation to work with different data sources - useful for things like stubbing out data before you've implemented your server-side AJAX handlers.根据您想要支持的复杂性,您可以添加其他功能,例如在特定时间间隔后使缓存过期、缓存多个调用(可能键入 AJAX URL)等。我喜欢保持 API 简单而不参考 ZA34A6659BCEAE779E - 这样你的缓存就像一个抽象的服务层,你可以创建其他缓存实现来处理不同的数据源 - 在你实现你的服务器端 AJAX 处理程序之前,对于像存根数据这样的事情很有用。

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

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