我希望我的函数(对控制器执行ajax调用)从响应中返回消息。
我试过这个,但它不起作用。如何才能达到我的目标?对此有更好的解决方案吗?
var exists = personExists ();
if (exists != null) {
alert('The person already exists');
return;
}
var personExists = function () {
var exists = false;
var errorMsg = null;
$.ajax({
url: "@Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
}
}
});
if (exists)
return errorMsg;
return null;
};
答案 0 :(得分:1)
您需要使用回调:
function getErrorMessage(message) {
//do whatever
}
在AJAX请求中:
$.ajax({
url: "@Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
getErrorMessage(response.message); //callback
}
}
});
答案 1 :(得分:1)
您可以使用回调函数执行此操作;
var personExists = function (callback) {
var exists = false;
var errorMsg = null;
$.ajax({
url: "@Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
callback(exists, errorMsg);
}
}
});
if (exists)
return errorMsg;
return null;
};
和用法;
personExists(function(exists, err) {
if (exists != null) {
alert('The person already exists');
return;
}
});
简单地说,您可以将exists
和errorMsg
传递给回调。有关回调函数