我有一个
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 });
解决方法
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',success: function(data) { $.each(data,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',value) { global_arr.push(value.name); }); alert(global_arr); //get correct value,works fine runOnComplete();//callback } }); //end of ajax function });