开发者

Function to return variable from ajax call

Im trying to make a function return a string from a ajax call.

This is my code:

function GetText(getThis) {  
    var current = GetMarketAndLang(开发者_StackOverflow社区);  
    var dataToReturn = "Error";  
    $.get('inc/ajaxGetText.php', {lang : current.lang, market : current.market, name : getThis},  
        function(data){  
            dataToReturn = data;  
    });  
    return dataToReturn;  
}

Using firebug i can see that the ajax call is correct but the whole function still returns the text "Error" instead of "and". Why is that and what can i do?

Thanks.


That is because of the asynchronous nature of the AJAX query – the function returns before the response is back. To solve this, you must use the full fledged $.ajax() function and set async to false:

function GetText(getThis) {  
    var current = GetMarketAndLang();  
    var dataToReturn = "Error";  

    $.ajax({
        url: 'inc/ajaxGetText.php',
        type: 'GET',
        async: false,
        success: function(data) {
            dataToReturn = data;
        }
    });

    return dataToReturn;
}

This forces the script to wait until the request has returned before the execution of the script can continue, thus, the variable is now the one returned from the AJAX call.


That's because the AJAX call is asynchronous. Your

function(data){  
    dataToReturn = data;  
}

does not run until after the asynchronous AJAX call is completed. The return dataToReturn will actually execute before the callback function in the AJAX call.

The ideal way to do this would be to call the function that uses the dataToReturn from the callback.

Alternatively pass in a function to GetText to be executed when the AJAX call is complete.


The ajax call is executing asynchronously, which is why "Error" is returned right away. To get the ajax results to return, you need to use $.ajax to do a synchronous GET.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜