jQuery中具有延迟/ajax的变量作用域

Variable scope with deferred / ajax in jQuery

本文关键字:ajax 变量 作用域 延迟 jQuery      更新时间:2023-09-26

我认为我使用的是非常标准的设置。单击元素以调用处理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结果呢?

您应该更改fetchMyData函数的作用。尝试返回promise对象。

$('<div>').click(function()
{
    var fetchMyDataPromise  = fetchMyData() ;
    fetchMyDataPromise.done(function(response)
    {
        console.log(response);
    });
});
function fetchMyData()
{
    return  $.ajax({ // ajax setup });
}  

你可以这样使用jQuery:

$('<div>')
    .on({
        click : function() {
           $.when(fetchMyData()).then(function(data) {
                    console.log(data);
           });
         }
    });
    function fetchMyData(){
        return $.ajax({
            // ajax setup
        });
    }

那么,如何使fetchMyData()在准备好后显示ajax结果呢?

您已经在.done回调中完成了此操作。如果您希望fetchMyData返回响应,则必须使用同步调用,这通常不是正确的做法(因为UI将冻结,直到响应到达)。


也许你想修改你的函数以进行回调:

function fetchMyData(thenDoThis){
    $.ajax({
        // ajax setup
    }).done(thenDoThis)
}
function doSomethingWithResponse(response) {
    // do something
}

然后这样称呼它:

fetchMyData(doSomethingWithResponse);

或者像这样:

$('<div>').click(function() {
    fetchMyData(function(response){
        console.log(response);
    });
});