我无法在 Jquery 中返回 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:数据未定义 我怎样才能返回数据?谢谢。抱歉我的英语不好,但我会说西类牙语。
最佳答案
Ajax 调用是异步的,因此您不能立即从它们返回值。相反,他们返回一个返回值的 promise ,因此您可以做的是:
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
});
关于javascript - AJAX 方法 Jquery 无法返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32980452/