0

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

4

3 回答 3

2

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

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

    var fetchMyDataPromise  = fetchMyData() ;

    fetchMyDataPromise.done(function(response)
    {
        console.log(response);
    });

});

function fetchMyData()
{
    return  $.ajax({ // ajax setup });
}  
于 2013-07-16T20:17:07.347 回答
1

你可以像这样使用 jQuery:

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

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

    function fetchMyData(){
        return $.ajax({
            // ajax setup
        });
    }
于 2013-07-16T20:30:19.080 回答
1

那么我怎样才能让 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);
    });
});
于 2013-07-16T20:06:48.077 回答