Ajax mất nhiều thời gian để hoàn thành. Việc thực thi hàm không mất nhiều thời gian. Vì vậy, do thời gian bạn nhận được để cảnh báo của bạn bên ngoài của yêu cầu ajax, yêu cầu ajax vẫn còn sử dụng thời gian để hoàn thành (hoặc trong truyền tải hoặc trong hành động phía máy chủ).
Bạn luôn có thể đợi phương thức ajax hoàn tất.
$(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
}
})()
});
Tuy nhiên, cách phổ biến nhất là sử dụng gọi lại.
$(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
});
Nguồn
2013-04-03 19:15:43
Câu hỏi yêu thích của chúng tôi, các cuộc gọi không đồng bộ! – epascarello