我试图将结果成功传递给另一个函数,并且它只是返回一个未定义的值:
function tagCustomer(email, tags) {
var o = new Object();
o.tags = tags;
o.email = email;
o.current_tags = getCustomerTags(email);
o.new_tags = tags;
console.log(o);
return true;
}
function returnData( data ) {
return data;
}
function getCustomerTags(email) {
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
data: {email: email, "action": "getCustomerTags"},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
returnData( data );
return data;
}
});
}
o.current_tags
应该得到的结果getCustomerTags
。
尝试一下(这对UI不利,但是使用您当前的代码也可以使用,另外,请查看我答案底部的“更好的实践”):
function getCustomerTags(email) {
var result = null;
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
async: false,
data: {
email: email,
"action": "getCustomerTags"
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
result = data;
}
});
return result;
}
您的代码无法正常工作的原因是$ .ajax成功函数返回了data
var,但未getCustomerTags
返回任何内容。另外,请注意“ async:false”,因为如果将其用作异步,则该函数将返回null,因为它将在ajax完成之前返回。
更好的实践
ajax函数具有一个回调(成功),请使用它!设计您的代码不是将其设计为等待ajax请求结果的方法,而是将其设计为在完成时会执行某些操作的ajax请求!
例
function tagCustomer(email, tags, data) {
var o = new Object();
o.tags = tags;
o.email = email;
o.current_tags = data
o.new_tags = tags;
console.log(o);
return true;
}
function getCustomerTags(email, tags) {
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
data: {email: email, "action": "getCustomerTags"},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
tagCustomer(email, tags, data);
}
});
}
如果您还有其他疑问,请随时发表评论。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句