在JavaScript回调函数中设置本地变量

时间:2021-09-13 19:35:45

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, array appears 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.

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

5 个解决方案

#1


7  

The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.

这里的问题是控制台。日志同步执行,而ajax调用异步执行。因此它在回调完成之前运行,所以它仍然认为数组是未定义的,因为还没有运行成功。为了使此工作,您需要延迟控制台。日志调用直到成功完成。

$(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();
    }});
});

#2


2  

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。

#3


1  

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

成功函数不会立即执行,而是在http -响应到达之后。因此,此时数组仍未定义。如果您想对http -响应数据执行操作,请在success函数中执行,或者在函数中定义该操作,然后在success回调中调用该函数。

#4


1  

Try calling a function to set this variable after your 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");
}
});

#5


0  

AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.

AJAX是异步的。您正在设置数组变量,但要等到执行了调试之后。进行AJAX调用会发送一个请求,然后在代码中继续。在以后的某个时候,请求返回并执行您的成功或错误函数。

#1


7  

The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.

这里的问题是控制台。日志同步执行,而ajax调用异步执行。因此它在回调完成之前运行,所以它仍然认为数组是未定义的,因为还没有运行成功。为了使此工作,您需要延迟控制台。日志调用直到成功完成。

$(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();
    }});
});

#2


2  

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。

#3


1  

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

成功函数不会立即执行,而是在http -响应到达之后。因此,此时数组仍未定义。如果您想对http -响应数据执行操作,请在success函数中执行,或者在函数中定义该操作,然后在success回调中调用该函数。

#4


1  

Try calling a function to set this variable after your 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");
}
});

#5


0  

AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.

AJAX是异步的。您正在设置数组变量,但要等到执行了调试之后。进行AJAX调用会发送一个请求,然后在代码中继续。在以后的某个时候,请求返回并执行您的成功或错误函数。