开发者

How can I return value from $.Ajax function?

function get_url(){
    var returnValue  = null;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
    开发者_运维问答        console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            }
    });

    console.log(returnValue); // "null"
    return returnValue;
}

Why function don't return "not_null" ?


That is because your ajax method is so call it another thread. Once you call it your method will continue, but value will be set once ajax call is done. So you can wait, this is bad solution but it can help:

function get_url(){
    var returnValue  = null;
    var _done = false;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
            console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            _done = true;
            }
    });
    while(!_done) { }
    console.log(returnValue); // "null"
    return returnValue;
}


You can't return the value from your ajax request. Because return is returning returnValue at once and not waiting for the ajax request.

If you want to receive the ajax response you can use a callback method:

function get_url(callback){
    var returnValue  = null;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
            console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            callback(returnValue);
        }
    });
}

And then call:

get_url(function(response) {
    console.log(response);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜