AJAX方法Jquery不能返回数据
AJAX method Jquery can't return data
我无法在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
}
我得到这个错误:Uncaught ReferenceError:数据没有定义我怎样才能归还数据?谢谢你!很抱歉我的英语不好,但我会说西班牙语。
Ajax调用是异步的,因此您不能立即从它们返回值。相反,它们返回一个返回值的承诺所以你可以做的是:
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
});
Ajax调用是异步的,因此您不能使用它们返回数据。如果你想使用这些数据,你需要使用回调函数来代替。
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);
});
正如其他人所说,由于请求是异步的,这是失败的。您可以按照他们的建议修复代码,通过异步处理它,或者您可以使用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;
}
您无法返回该项目,因为它已不存在。尝试先定义它,像这样:
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调用并在Node中获取返回数据
- 角度服务未返回数据
- 统计ajax返回数据中的html元素
- 有没有更好的方法可以测量从Ajax调用返回数据所需的总时间
- Imgur API图像搜索未返回数据
- javascript对象显示为null,但object.properties返回数据
- 如何从ajax调用JQuery返回数据
- 试图从嵌套的回调函数返回数据
- NodeJS FS 不从多个文件返回数据
- ajax函数未在C#中返回数据
- 如何在公共js模块中从web服务返回数据
- 将字符串与 JSON 对象组合以返回数据
- 嵌套异步函数未及时返回数据的问题
- NodeJS JSONStream 以一个长字符串的形式返回数据
- 如何使用 HTML 图像请求将数据发送到服务器,或返回数据作为响应
- 从 Angular 模态服务中的模态主体模板返回数据
- jQuery 每个循环返回数据两次
- $.getJSON 在返回数据后不会运行函数
- 如何访问返回数据中的特定json值
- 工厂返回数据后未设置角度$scope