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

jQuery 表單驗證後 AJAX 提交再跳轉:避免 window.location.href 直接跳過驗證

     編輯:程式設計疑難解答

表單驗證通過後想「先 AJAX 提交資料到 PHP,成功再跳轉 `list.php`」。直接用 `window.location.href` 會導致瀏覽器立即跳轉,**截斷 AJAX 請求**,資料未送達後端。正確做法是在 AJAX `success`/`done` 回調中跳轉。

錯誤代碼(同步跳轉截斷 AJAX)

function sublime() {
    if ($('#name,#message').val().length < 1) { alert("請輸入必填項"); return; }
    if ($('#qq').val().length < 1 || $('#telphone').val().length < 1) { alert("請輸入選填項"); return; }
    if ($('#telphone').val().length < 10) { alert("請輸入正確的手機號碼"); return; }

    window.location.href = "list.php";  // ❌ 立即跳轉,AJAX 還沒發出就被取消
}

正確代碼:AJAX 成功回調跳轉

function sublime() {
    // 1. 驗證
    if ($('#name,#message').val().length < 1) { alert("請輸入必填項"); return; }
    if ($('#qq').val().length < 1 || $('#telphone').val().length < 1) { alert("請輸入選填項"); return; }
    if ($('#telphone').val().length < 10) { alert("請輸入正確的手機號碼"); return; }

    // 2. 收集資料
    var data = {
        name: $('#name').val(),
        message: $('#message').val(),
        qq: $('#qq').val(),
        telphone: $('#telphone').val()
    };

    // 3. AJAX 提交
    $.ajax({
        url: 'saveData.php',           // 後端處理檔案
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(resp) {
            if (resp.success) {
                alert('儲存成功');
                window.location.href = 'list.php';  // ✅ 成功後跳轉
            } else {
                alert('儲存失敗:' + resp.msg);
            }
        },
        error: function(xhr, status, err) {
            alert('請求異常:' + err);
        }
    });
}

// 按鈕綁定
$('#submitBtn').click(sublime);

後端 PHP 回應格式 (saveData.php)

prepare("INSERT INTO msgs (name,msg,qq,tel) VALUES (?,?,?,?)")->execute([...]);

echo json_encode(['success' => $success, 'msg' => $msg]);

關鍵差異對照

做法行為資料是否送達
`window.location.href` 直接寫在驗證後瀏覽器**立即卸載頁面**,進行中請求全部取消❌ 否
`$.ajax` + `success` 回調裡 `location.href`請求完成、收到回應**後**才跳轉✅ 是
`$.post(...).done(fn).always(fn)`Promise 鏈式,語意更清晰✅ 是
`fetch(...).then(r=>r.json()).then(...)`現代標準 API,無 jQuery 依賴✅ 是

進階:防止重複提交

function sublime() {
    var $btn = $('#submitBtn').prop('disabled', true).text('提交中...');
    // ... 驗證 ...
    $.ajax({
        // ...
        complete: function() {
            $btn.prop('disabled', false).text('提交');
        }
    });
}

一句話總結

**驗證 → AJAX → 回調裡跳轉**,不要在 AJAX 發送前/發送中寫 `window.location.href`,否則請求會被瀏覽器取消導致資料丟失。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved