简体   繁体   English

从嵌套异步ajax调用返回结果

[英]Return result from nested asynchronous ajax call

I need to return the data from an nested ajax call but also need the ajax call to stay asynchronous. 我需要从嵌套的ajax调用返回数据,但也需要ajax调用保持异步。

I found some related questions but can't get it to work in the situation below. 我发现了一些相关问题,但在以下情况下无法正常工作。 I assume returnData is being returned before the ajax call is done, but I can't find an solution. 我假设在ajax调用完成之前返回returnData ,但是我找不到解决方案。

function makeRequest(command, postData){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        returnData = data;
    });

    return returnData;
}

Yes since this call is async returnData is returned immediately. 是,因为此调用是异步的,returnData将立即返回。 If you need to use returndata pass it to a function in the callback 如果您需要使用returndata,请将其传递给回调函数

function makeRequest(command, postData, functionToCallAfterAjax){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        functionToCallAfterAjax(data);
    });


}

Of course you could pass the function to call as a parameter. 当然,您可以将函数作为参数传递。

This means that if your code was meant to do: 这意味着如果您的代码打算这样做:

var returnedData = makeRequest(command, postData);
anotherFunction(returnedData);

you should do simply (using the code above) 您应该简单地做(使用上面的代码)

makeRequest(command, postData, anotherFunction);

and everything will work 一切都会正常

You can't. 你不能 Asynchronous events don't work like that. 异步事件不能那样工作。

The HTTP request is sent, then the function that triggers it continues immediately . 发送HTTP请求,然后触发它的功能立即继续 The callback won't be fired until the HTTP response has arrived, but which time the calling function will have ended. 在HTTP响应到达之前,不会触发回调,但是调用函数将在该时间结束。

You must have your callback (the function you are passing to done() ) perform whatever further processing is needed. 您必须让回调(传递给done()的函数)执行所需的任何进一步处理。

You're returning the value of returnData before the .done() function has run. 您将在.done()函数运行之前返回returnData的值。 Correct your code by passing the received data to a function for processing: 通过将接收到的数据传递给函数进行处理来更正代码:

function makeRequest(command, postData){
    $.ajax({
        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'
    }).done(function(data){
        HandleCallBack(data);
    });
}

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

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