我有在保存时验证重复名称的表单,并且我使用 webapi 进行处理。下面是一个示例函数,它通过单击按钮调用 onclick="return validateName()"
。
function validateName() {
var nam = $('#frmeditCategory input[id="Name"]').val();
var result = false;
$.ajax({
type: "POST",
url: "/Admin/CategoryName",
data: { Name: "test"},
dataType: "json",
success: function (response) {
if (response.message == true) {
alert("Category already exists.");
result = false;
alert(0);
return false;
}
else {
result = true;
alert("1");
return true;
}
},
error: function (xhr, ajaxOptions, thrownError) { alert("some error occured"); result = false; }
});
alert("2");
return false;
}
这里 alert("2");
首先执行,然后 ajax 开始工作。我很困惑,我不知道我做错了什么。请帮帮我!
最佳答案
alert("2")
需要放在 $.ajax
的 promise 回调中:
$.ajax({
type: "POST",
url: "/Admin/CategoryName",
data: { Name: "test"},
dataType: "json",
success: function (response) {
if (response.message == true) {
alert("Category already exists.");
result = false;
// Why are the following here, they will never get called?
// alert(0);
// return false;
} else {
// Why is this line here, you never use it?
// result = true;
alert("1");
return true;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("some error occured");
result = false;
}
}).done(function () {
alert("2");
});
关于javascript 不能按正确的顺序工作 if-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035062/