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

标签 javascript jquery ajax get

所以我在这个函数中进行了一个ajax调用,有点像这样:

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

我在另一个函数中所做的是进行第二次调用,如下所示:

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

     }
  })
}

所以我真的想避免调用第二个电话。有什么好的方法可以避免这种情况吗?也许做一些链接或类似的操作,重用第一个回调?我听说打几个电话是不好的做法。 问候

感谢所有回答的人。最终没有使用任何解决方案,我用另一种方式解决了。我确信你给我的大多数例子都非常好。不知道如何接受答案。全部接受还是全不接受?!谢谢!

最佳答案

您可以创建一个简单的数据存储:

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

关于javascript - 避免第二次 ajax 调用的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336414/

相关文章:

javascript - Canvas 可以在手机上拉伸(stretch),但不能在电脑上拉伸(stretch)

jquery - 根据浏览器语言显示div,具有显示/隐藏功能(错误: nothing shows up)

jquery - 使用 jQuery 居中图片库,数学计算

php - 使用按钮使用文本框中的值更新数据库字段,它显示空白值

python - 如何让 Cloudfiles FormPost 返回 "Access-Control-Allow-Origin" header 以启用 CORS?

javascript - ajax 查询中的 & 符号被忽略

javascript - 有没有办法同时捕获同一类型的多个事件?

javascript - 如何避免此 Javascript 代码片段中的代码重复

javascript - 在 Ajax 中使用数组

jquery - 修改简单的 jQuery 脚本以使用计时器随机化文本