【问题标题】:Returning variables inside JS / JSON functions在 JS/JSON 函数中返回变量
【发布时间】:2010-07-30 20:10:40
【问题描述】:

我正在尝试理解 JS 中的 JSON、回调等。从下面更改的示例中,您将看到我在 $.getJSON 的函数回调中。然后,我跳入 getSomething() 并期望它改变我的结果变量。它会在函数范围内改变它,但当我跳出该函数时不会。

您会从 2 个 console.log() 中看到,第一个显示正确,而第二个显示不正确。我确定我的问题的答案与通过返回变量有关。回调,但有人可以启发
我 :)

谢谢!

代码:

$.getJSON('/cart.js', function (cart, textStatus) {
  var result = '';
  result += 'Sample Stuff';
  StackOverflow.getSomething(param1, param2, function(a, b) {
    for(j=0; j < b.length; j++) {
      if (b.options[j] != 'Default Title') {
        if (a.options[j].name.indexOf("Color") > -1) {
          result += b.options[j].name;
          console.log(result); // <-- It comes out correct (Sample Stuff + b.options...)
        }
      }
    }
  });
  console.log(result); // <-- It comes out incorrect, just (Sample Stuff)
});

【问题讨论】:

    标签: javascript jquery json return-value


    【解决方案1】:

    我猜StackOverflow.getSomething() 运行 AJAX 请求?因此,在 AJAX 请求完成之前,不会执行在其回调中定义的内容(循环通过 ab)。发生的情况是StackOverflow.getSomething 被触发,然后在代码末尾的console.log(result) 之后立即执行。到那时,StackOverflow.getSomething 的回调还没有运行,result 还没有更新。仅记录“示例内容”。但是,当 AJAX 请求(getSomething)之后的回调中执行第二个 console.log 时,result 会更新并“正确”记录。

    也就是说,执行顺序是这样的

    1. result 设置为“样本”
    2. StackOverflow.getSomething() 触发带有附加回调函数的 AJAX 请求
    3. console.log(result) 记录“样本”
    4. ajax 回调完成并触发其回调函数。 result 通过迭代 ab 相应更新
    5. 回调函数的console.log(result)记录result的最终值

    【讨论】:

    • 感谢您的解释。我想我可能已经假设了大部分,但仍然不知道如何将 getSomething() 的“结果”绑定到 getJSON() 以便它在 getJSON() 的其余部分执行之前发生。跨度>
    • 如果您依赖result 正确地使getJSON 的其余部分正常运行,则必须将其余的getJSON 代码放入StackOverflow.getSomething 的回调中:)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    相关资源
    最近更新 更多