Jquery .ajax()局部变量无法赋值给全局

我有一个jquery ajax代码如下:

$(document).ready(function() { var global_arr = new Array(); $.ajax({ url: 'result.php', type: 'post', dataType: 'json', success: function(data) { $.each(data, function(key, value) { global_arr.push(value.name); }); alert(global_arr); //get correct value, works fine } }); //end of ajax function alert(global_arr); //get null, it doesn't work properly }); 

注意提醒global_arr的行,为什么我不能从$ .ajax()函数中获取值? 谢谢任何人的帮助。

Ajax需要时间来完成。 函数执行时间不会太长。 因此,当您在ajax请求之外获得警报时,ajax请求仍然使用时间来完成(在传输或服务器端操作中)。

您始终可以等待ajax方法完成。

 $(document).ready(function() { var global_arr = new Array(); var complete = false;//flag to wait for ajax completion $.ajax({ url: 'result.php', type: 'post', dataType: 'json', success: function(data) { $.each(data, function(key, value) { global_arr.push(value.name); }); alert(global_arr); //get correct value, works fine complete = true;//mark ajax as complete } }); //end of ajax function (function runOnComplete(){ if( complete ){//run when ajax completes and flag is true alert(global_arr); }else{ setTimeout(runOnComplete,25);//when ajax is not complete then loop } })() }); 

但是,最常见的方法是使用回调。

 $(document).ready(function() { function runOnComplete(){//code executes once ajax request is successful alert(global_arr); } var global_arr = new Array(); $.ajax({ url: 'result.php', type: 'post', dataType: 'json', success: function(data) { $.each(data, function(key, value) { global_arr.push(value.name); }); alert(global_arr); //get correct value, works fine runOnComplete();//callback } }); //end of ajax function }); 

Ajax是异步的。 当JS引擎到达你的无效alert()行时,AJAX调用还没有机会从服务器获得响应并设置变量。

这就是内部alert()有效的原因。 当响应从服务器进入时它会被执行。

那是因为alert(global_arr); //get null, it doesn't work properly alert(global_arr); //get null, it doesn't work properly$.ajax完成之前运行alert(global_arr); //get null, it doesn't work properly

我在这里的建议是将其分解为3个function,这样会更有意义。 你需要ajax,handelRequest,onComplete。 您可能还想为您的ajax函数添加error handling程序,因此如果它失败了,它可以通过锁定用户的脚本来完成。

 $(document).ready(function () { var global_arr = new Array(); $.ajax({ url: 'result.php', type: 'post', dataType: 'json', success: handelRequest(data), error: handleError }); function handelRequest(data) { $.each(data, function (key, value) { global_arr.push(value.name); }); onComplete(global_arr); //get correct value, works fine } function onComplete(global_arr){ // then here you can do what ever you // you would like with the array alert(global_arr); } function handleError(){ // gracefully fail } })