首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

AJAX 同步請求 async: false 解決 return true 不生效問題

     編輯:程式設計綜合問答

現象

$.ajax 預設非同步,success 回調中的 return true 僅返回給 AJAX 內部,外層函式 isExit() 已繼續執行至 return false。

解決方案

方案一:async: 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;
}

方案二:Promise / async-await (現代、非阻塞)

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 甚至標記為棄用警告。
  • **全面採用 Promise/async-await**:程式碼線性、易讀、易除錯。
  • 表單提交攔截:onsubmit="return onSubmit()" 中 onSubmit 必須回傳 Promise 或同步 boolean;若非同步,需 event.preventDefault() 手動控制提交時機。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved