如何从$ .Ajax函数返回值?

时间:2011-08-12 11:25:44

标签: jquery

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;
}

为什么函数不返回“not_null”?

2 个答案:

答案 0 :(得分:2)

那是因为你的ajax方法是另一个线程。一旦你调用它,你的方法将继续,但是一旦ajax调用完成,将设置值。所以你可以等,这是一个糟糕的解决方案,但它可以帮助:

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;
}

答案 1 :(得分:2)

您无法从ajax请求中返回该值。因为return一次返回returnValue而不是等待ajax请求。

如果您想收到ajax响应,可以使用回调方法:

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);
        }
    });
}

然后致电:

get_url(function(response) {
    console.log(response);
});
相关问题