【问题标题】:how to access variable in function from out of function in javascript [duplicate]如何从javascript中的函数外访问函数中的变量[重复]
【发布时间】:2020-06-30 10:18:08
【问题描述】:

我在 JavaScript 中有一个 totalPrice 变量:

var totalPrice = 0;

使用 AJAX,我向服务器发送请求并从中获取结果,我希望将服务器结果分配给 totalPrice

$.request('onGetProductId', {
    data: { productId: productValue },
    success: function (data) {
        totalPrice = data.result;
    }
});
alert(totalPrice) // This line i want to get server's response but i get zero.

当我从 AJAX 调用 totalPrice 时,我得到 0 值,但我想在 data.result 中获取值。我该如何解决?

【问题讨论】:

  • 这取决于var totalPrice = 0; 相对于您的AJAX 代码的位置,请粘贴更多相关代码,以便我们了解问题所在。
  • 我认为您在 ajax request 之后得到了 totalPrice 的值。您需要等到收到回复并更新totalPrice。因为ajax requestsasynchronous
  • @GhassenLouhaichi ,我想在 ajax 请求调用后访问 totalPrice 并使用服务器的响应设置 totalprice 值。当我在 Ajax 请求后调用 totalPrice 时,我得到零值但我想获得服务器的响应,我编辑我的代码请再看一遍。
  • "我该如何解决?" - 在成功回调中移动 alert(或任何使用 totalPrice 的东西)。

标签: javascript ajax function variables scope


【解决方案1】:

简短的回答:你不能。你的 AJAX 调用是异步的,这意味着成功函数会在天知道什么时候执行。

您在脚本中在其下方编写的代码无法访问该代码片段,因为它很可能在 ajax 调用被解析之前执行。

如果您想使用从 ajax 调用中获得的结果来更改 DOM,则需要在成功函数中进行。如果您绝对需要在代码的其他地方重用该值,您可以从 DOM 中获取它,但我建议您谨慎行事。

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多