$.ajax 預設非同步,success 回調中的 return true 僅返回給 AJAX 內部,外層函式 isExit() 已繼續執行至 return false。
function isExit() {
var result = false;
$.ajax({
url: "deptIsExit",
type: "post",
async: false, // 關鍵:同步等待
data: { deptValue: $('#testDept').val() },
success: function(data) {
$('#message').html(data.result.message);
result = data.result.isExit; // 賦值給外層變數
}
});
return result;
}
function checkExit(value) {
return $.post("deptIsExit", { deptValue: value })
.then(res => res.result.isExit);
}
async function onSubmit() {
if (await checkExit($('#testDept').val())) {
return true; // 表單提交
}
return false;
}
function isExit(callback) {
$.post("deptIsExit", { deptValue: $('#testDept').val() }, function(data) {
callback(data.result.isExit);
});
}
// 使用
isExit(function(exists) {
if (exists) { form.submit(); }
});
async: false**:會凍結瀏覽器主執行緒,Chrome 甚至標記為棄用警告。onsubmit="return onSubmit()" 中 onSubmit 必須回傳 Promise 或同步 boolean;若非同步,需 event.preventDefault() 手動控制提交時機。