AJAX 方法 Jquery 不能 return 数据

AJAX method Jquery can't return data

我无法在 Jquery 中 return ajax 请求的值。这是我的代码:

    function ajaxUniversal(datos, url) {
    $.ajax({
        url: url,
        data: {
            valores: datos
        },
        type: "POST",
        dataType: "html",
        success: function (data) {
            console.log("Datos recibidos: "+data)
            return data; //This does not returns the data
        },
        error: function (errorThrown) {
            return false;
        }
    });
}

如果我在最后添加 return 语句:

function ajaxUniversal(datos, url) {
    $.ajax({
        url: url,
        data: {
            valores: datos
        },
        type: "POST",
        dataType: "html",
        success: function (data) {
            console.log("Datos recibidos: "+data)
            return data;
        },
        error: function (errorThrown) {
            return false;
        }
    });
    return data;//This is the statement but not works
}

我收到这个错误: 未捕获的 ReferenceError:数据未定义 我如何 return 数据?谢谢你。抱歉我的英语不好,但我会说西班牙语。

Ajax 调用是异步的,因此您不能 return 数据。如果要使用该数据,则需要改用回调函数。

function ajaxUniversal(datos, url, callback) {
    $.ajax({
        url: url,
        data: {
            valores: datos
        },
        type: "POST",
        dataType: "html",
        success: function (data) {
            console.log("Datos recibidos: "+data)
            callback(data);
        },
        error: function (errorThrown) {
            callback(errorThrown);
        }
    });
}

其他地方...

ajaxUniversal(someData, someUrl, function(data){
    // Do work with data here
    console.log(data);
});

您无法 return 该项目,因为它已不存在。尝试先定义它,如下所示:

function ajaxUniversal(datos, url) {
    var returlVal;
    $.ajax({
        url: url,
        async: false, 
        data: {valores: datos},
        type: "POST",
        dataType: "html",
        success: function (data) {
            console.log("Datos recibidos: "+data)
            returlVal = data;
        },
        error: function (errorThrown) {
            returlVal = false;
        }
    });
    return returlVal;
}

Ajax 调用是异步的,因此您不能 return 立即从它们中获取值。相反,他们 return 承诺 return 一个值,所以你可以做的是:

function ajaxUniversal(datos, url, callback) {
return $.ajax({
    url: url,
    data: {
        valores: datos
    },
    type: "POST",
    dataType: "html"
});
}

并这样称呼它:

ajaxUniversal( datos, url, callback ).then( function(data){

     //manipulate data here

});

正如其他人所说,这是由于请求是异步的而失败的。您可以按照他们的建议通过异步处理来修复您的代码,或者您可以使用 async: false.

将请求设置为同步
function ajaxUniversal(datos, url) {
    var data;
    $.ajax({
        url: url,
        async: false,  // <---- this will cause the function to wait for a response
        data: {
            valores: datos
        },
        type: "POST",
        dataType: "html",
        success: function (data) {
            console.log("Datos recibidos: "+data)
            data = data;
        }
    });
    return data;
}