繁体   English   中英

jQuery中具有延期/ ajax的可变范围

[英]Variable scope with deferred / ajax in jQuery

我使用的是相当标准的设置。 单击元素以调用处理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 });
}  

那么,如何使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);
    });
});

您可以像这样使用jQuery When:

$('<div>')
    .on({
        click : function() {

           $.when(fetchMyData()).then(function(data) {
                    console.log(data);
           });
         }
    });

    function fetchMyData(){
        return $.ajax({
            // ajax setup
        });
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM