我有一个java脚本函数
function myfunction() {
var url = location.href;
var ajaxRespose;
$.ajax({
type:"GET",
url: url,
cache:false,
dataType: "text",
success: function(response) {
var data = $.parseJSON(response);
ajaxRespose = data;
console.debug("ajaxRespose ==>:"+ajaxRespose);
}
});
console.debug("first ajaxRespose: " +ajaxRespose);
}
return false;
}
在我的控制台(firbug)上我得到:
first ajaxRespose: undefined
ajaxRespose ==>:[object Object]
我的问题是,为什么 ajax 调用在“第一个”console.debug 之后执行。 PS:我已经简化了函数,(函数工作正常,但问题在于执行顺序)
最佳答案
因为 $.ajax()
是异步,所以事件的发生顺序如下:
$.ajax(...); // executes AJAX request
console.debug("first ajaxResponse:" + ajaxRespose); // undefined
/* some time later, we receive AJAX response */
// it executes the success function from the original AJAX request
console.debug("ajaxRespose ==>:"+ajaxRespose); // [object Object]
关于javascript - 函数内容执行不按顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15760362/