use*_*859 7 javascript ajax jquery
我有一个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
});
Run Code Online (Sandbox Code Playgroud)
注意提醒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
}
})()
});
Run Code Online (Sandbox Code Playgroud)
但是,最常见的方法是使用回调.
$(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
});
Run Code Online (Sandbox Code Playgroud)
Ajax是异步的.当JS引擎到达你的无效alert()行时,AJAX调用还没有机会从服务器获得响应并设置变量.
这就是内部alert()有效的原因.当响应从服务器进入时它会被执行.
| 归档时间: |
|
| 查看次数: |
8568 次 |
| 最近记录: |