Ajax在返回值之前等待响应

时间:2015-12-03 04:49:42

标签: javascript jquery ajax

基本上我在让程序等待AJAX​​请求完成时遇到问题。我似乎无法获得返回值,除了在下面的示例代码中test()函数中未定义的任何内容,它调用getFriends()。我可以使它在ajax调用中将async设置为false,但由于不推荐使用,我想避免使用此解决方案。

我已经尝试使用延迟解决问题和我在堆栈上发现的许多其他选项溢出没有运气所以我得出结论我可能使用延迟错误或(不太可能)延迟不是选项在这里,所以我希望这个网站上的一个有才能的人可以帮助我!

查看下面的代码;它是我运行的简单版本。提前谢谢!

//function that shows how the function with issue should be called/used
function test(){
    var result = getFriends(127, 1); //this is getting a result returned before ajax is done so the result is undefined

    //do stuff with result data
    console.log(result);
}


//function that creates a data object and calls my custom ajax function
function getFriends(user_id, page_no){

    //create data object containing given parameters and a data type parameter
    var data = {
        page_no: page_no,
        profile_id: user_id,
        request_type: 'get_friends' 
    };

    //call friendAjax to get users friends
    var response = friendAjax(data, 'kv_people_feed');
    return response;
}



//Used for all friend related ajax requests. Accepts a data object to be sent as parameters and otional url.
function friendAjax(data, url){
    url = typeof url !== 'undefined' ? url : 'friendsLibrary'; //allows optional url param
    $.ajax({
        // async: false,
        url: Config.home + '/' + url + '/', //dynamic url
        data: data,
        dataType: 'jsonp',
        success: function(response){
            console.log(response);
            return response;
        }
    });
}

1 个答案:

答案 0 :(得分:1)

问题是$.ajax是异步执行的。 friendAjax()在你调用ajax之前返回。此外,您的回报是在匿名函数内返回以获得成功。

您可以将一个回拨添加回friendAjax来解决此问题。

function friendAjax(data, url, callback){
    url = typeof url !== 'undefined' ? url : 'friendsLibrary'; //allows optional url param
    $.ajax({
        // async: false,
        url: Config.home + '/' + url + '/', //dynamic url
        data: data,
        dataType: 'jsonp',
        success: function(response){
            console.log(response);
            callback(response);
        }
    });
}

然后当你打电话时:

friendAjax({}, "http://wherever.com", function(data){
    // Data will be defined here.
    console.log(data);
}