萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Ajax 實現表單異步提交完整實戰代碼

基於 jQuery Ajax 的表單異步提交最佳實踐

傳統表單提交會導致頁面重載,影響用戶體驗。使用 jQuery 的 $.ajax() 配合 serialize() 方法,能輕鬆實現無刷新表單提交,並靈活處理服務端響應。

核心實現代碼

$.ajax({
  url: "mobileSurveyAction_addSurvey.action",  // 提交地址
  data: $("#form1").serialize(),               // 表單數據序列化
  type: "POST",
  dataType: "json",
  success: function(result) {
    if (result.success === '100') {
      $("#mySection").hide();
      $(".footer").hide();
      $("#alertMsg").show();
    } else {
      alert("提交失敗!");
    }
  },
  error: function(xhr, status, error) {
    console.error("請求異常:", error);
    alert("網絡錯誤,請稍後重試");
  }
});

關鍵技術點解析

  1. serialize():自動收集表單內所有帶 name 屬性的輸入控件值,拼接為標準查詢字符串
  2. dataType: "json":指定預期響應格式,jQuery 會自動解析 JSON
  3. 錯誤處理:生產環境務必添加 error 回調,捕獲網絡異常
  4. 防重複提交:建議在 beforeSend 中禁用提交按鈕,complete 中恢復

增強版模板(含載入狀態)

$("#form1").on("submit", function(e) {
  e.preventDefault();
  const $btn = $(this).find(":submit").prop("disabled", true);
  
  $.ajax({
    url: this.action,
    type: this.method,
    data: $(this).serialize(),
    dataType: "json"
  }).done(function(res) {
    // 處理成功邏輯
  }).fail(function() {
    alert("提交異常");
  }).always(function() {
    $btn.prop("disabled", false);
  });
});

這種模式廣泛應用於登入、註冊、搜索、評論等場景,是現代 Web 開發的基礎技能。

copyright © 萬盛學電腦網 all rights reserved