我认为我正在使用非常标准的设置。单击元素以调用处理 ajax 请求的函数。
在使用异步任何东西并试图弄清楚jQuery 延迟时,我对变量范围和回调的有限理解让我微弱的大脑受伤。
$('<div>')
.on({
click : function(){
console.log(
fetchMyData() // this will be 'undefined' but why?
)
}
})
function fetchMyData(){
$.ajax({
// ajax setup
})
.done(function(response){
console.log( response ); // shows 'hello' as expected
return response;
})
}
我知道 ajax 调用不一定会在我执行 console.log() 时完成,因为它当然是异步的。
那么我怎样才能使它fetchMyData()
一旦准备好就会显示ajax结果呢?