在 JavaScript 回调函数中设置局部变量 [英] Setting local variable in a JavaScript callback function
问题描述
我对 JavaScript 比较陌生,我以为我知道回调函数是如何工作的,但在网上搜索了几个小时后,我仍然不明白为什么我的代码不起作用.
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.
我正在发出一个返回字符串数组的 AJAX 请求.我正在尝试将此数组设置为局部变量,但一旦执行回调函数,它似乎就失去了它的值.
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.
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);
在控制台中,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.
推荐答案
这里的问题是 console.log
是同步执行的,而 ajax 调用是异步执行的.因此它在回调完成之前运行,所以它仍然将 array
视为 undefined
因为 success
还没有运行.为了完成这项工作,您需要将 console.log
调用延迟到 success
完成之后.
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.
$(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();
}});
});
这篇关于在 JavaScript 回调函数中设置局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!