在 JavaScript 回调函数中设置局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9368597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:25:57  来源:igfitidea点击:

Setting local variable in a JavaScript callback function

javascriptjqueryajaxcallback

提问by Alex

I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.

我对 JavaScript 比较陌生,我以为我知道回调函数是如何工作的,但是在网上搜索了几个小时后,我仍然不明白为什么我的代码不起作用。

I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.

我正在发出一个返回字符串数组的 AJAX 请求。我试图将此数组设置为局部变量,但一旦执行回调函数,它似乎就失去了它的值。

    var array;

    $.ajax({
        type: 'GET',
        url: 'include/load_array.php',
        dataType: 'json',
        success: function(data){
            array = data;
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("Error loading the data");
        }
    });

    console.debug(array);

In the console, arrayappears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.

在控制台中,array显示为未定义。任何人都可以向我解释为什么没有设置它以及如何在回调函数中设置局部变量。

采纳答案by JaredPar

The problem here is that console.logexecutes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees arrayas undefinedbecause successhasn't run yet. In order to make this work you need to delay the console.logcall until after successcompletes.

这里的问题是console.log同步执行而ajax调用异步执行。因此它,所以它仍然认为回调完成之前运行arrayundefined,因为success还没有运行。为了完成这项工作,您需要将console.log调用延迟到success完成之后。

$(document).ready(function() {
    var array;

    var runLog = function() {
      console.log(array); 
    };

    $.ajax({
      type: 'GET',
      url: 'include/load_array.php',
      dataType: 'json',
      success: function(data){
        array = data;
        runlog();
    }});
});

回答by GoldenNewby

The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.

ajax 中的第一个 A 是用于异步的,这意味着当您调试数组时,结果仍未交付。数组在显示其值时未定义。您需要在 array = data 下执行 console.debug。

回答by ?ime Vidas

The successfunction doesn't execute immediately, but only after the HTTP-response arrives. Therefore, arrayis still undefinedat this point. If you want to perform operations on the HTTP-response data, do it from within the successfunction, or alternatively, define that operation inside of a function and then invoke that function from within the successcallback.

success函数不会立即执行,而是仅在 HTTP 响应到达后执行。所以,array还停留undefined在这一点上。如果要对 HTTP 响应数据执行操作,请从success函数内部执行操作,或者,在函数内部定义该操作,然后从success回调内部调用该函数。

回答by adis

Try calling a function to set this variable after your success:

尝试在您之后调用一个函数来设置这个变量success

var array;

var goodToProceed = function(myArr) {
   console.debug(myArr);
};

$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
    goodToProceed(data);
},
error: function(jqXHR, textStatus, errorThrown){
    alert("Error loading the data");
}
});

回答by James Montagne

AJAX is asynchronous. You are setting the arrayvariable, but not until after that debugexecutes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your successor errorfunctions execute.

AJAX 是异步的。您正在设置array变量,但直到debug执行之后才设置。进行 AJAX 调用会发送一个请求,但随后会继续执行代码。稍后,请求返回并且您的successerror函数执行。