【问题标题】:global variable is showing blank always in jquery全局变量在jquery中总是显示空白
【发布时间】:2017-07-26 00:20:10
【问题描述】:

我在 jquery 中创建了一个全局变量。然后我创建了一个函数,在其中我进行 jquery get 调用并将响应变量设置为全局变量。当我对该全局变量执行 console.log 时,它总是显示为空白。我做的代码是

var currentname = "";
function getcurrentname() {
    $.get(
        url
    ).success(function(response) {
        response = JSON.parse(response);
        currentname = response.name;
    });
}
getcurrentname();
console.log(currentname);

那么我应该如何在全局范围内使用该变量。

【问题讨论】:

  • .get() 是异步的,因此您的 console.log 在 .get() 完成之前执行。将console.log 移动到成功函数中。
  • 那么我将如何使用该全局变量。
  • 其实你在JavaScript中创建了一个全局变量。您已经在全球范围内使用它。在您的代码中唯一使用 jQuery 是进行 asynchronous 调用,成功时(提示)为您的变量分配一个值。
  • 我想在全球范围内使用响应。

标签: jquery


【解决方案1】:

你应该在 ajax 请求中使用 async : false

【讨论】:

  • 这方面的任何例子。
  • 不,你不应该,你应该重构代码来处理异步。
  • 你可以使用这个代码 $.ajax({ url: url, async:false, complete: function (response) { response = JSON.parse(response); currentname = response.name; } } );
猜你喜欢
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多