【问题标题】:How to change global variable in jquery get method? [duplicate]如何在 jquery get 方法中更改全局变量? [复制]
【发布时间】:2018-08-06 22:14:32
【问题描述】:

我不是 js 新手,但是 jquery get 方法有一个愚蠢的问题,它不能更改全局变量,我不知道为什么?

function getData(data) {
    re=null;
    $.get("http://example.com/api.php",{ d:data}).done(function(result){

            re = true;

        }).fail(function(){

            re = false;

        });
        console.log(re);
        return re;
}

如果您看到console,它仍然是null
有什么想法吗?

更新:

我的问题不在于console.log(),实际上问题是我不能像这样存储和返回值:

alert(getData(data));

这仍然返回 null。

【问题讨论】:

  • 这是因为当您调用console.log 时,get 调用还没有结束。您必须将console.log 放入donefail 回调中。
  • ajax 是异步的,你可以 console.log(re) 在你的 done 或 fail 回调中
  • @xianshenglu 我要返回值
  • 你不能因为 AJAX 调用是异步的。您需要改用回调模式。请参阅我标记的副本以获取更多信息
  • @Rory McCrossan 谢谢你提到另一个问题,但我认为我的问题有点不同,我想将callback() 的结果存储在像re 这样的全局变量中。你能帮我解决这个问题还是重新打开问题来更新它?

标签: javascript jquery get xmlhttprequest return


【解决方案1】:

这是因为 $.get 是一个异步调用,当 re 变量被重新分配一个新值时,console.log 正在执行。

您可以在调用异步函数 getData(data) 时使用回调函数。

function getData(data,callback) {
$.get("http://example.com/api.php",{ d:data}).done(function(result){

        callback(true)

    }).fail(function(){

        callback(false);

    });
}
//call it with your data and callback function
getData(data, function(response){
     console.log(response); // this will contain true or false as returned from your getData function.
})

我希望这会有所帮助。

【讨论】:

  • 这不是答案。你只是解释问题
  • 感谢您的回答,但这与 put console.log() 而不是 callback() 相同。你能告诉我如何将response 存储在像re 这样的全局变量中吗?
猜你喜欢
  • 2017-05-13
  • 2012-08-01
  • 1970-01-01
  • 2014-11-23
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
相关资源
最近更新 更多