萬盛學電腦網

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

jQuery AJAX 請求三大常用模式匯總:從基礎配置到表單序列化提交

模式一:完整配置 $.ajax()(最靈活、功能最全)


$.ajax('/api/users', {
  type: 'POST',                    // HTTP 方法
  data: { name: 'John', age: 30 }, // 發送數據(對象自動序列化為 query string)
  dataType: 'json',                // 預期返回類型:json/xml/html/script/text
  contentType: 'application/json', // 請求頭 Content-Type(發送 JSON 時需設置)
  timeout: 5000,                   // 超時毫秒數
  
  // 成功回調
  success: function(response, textStatus, jqXHR) {
    console.log('數據:', response);
  },
  
  // 失敗回調
  error: function(jqXHR, textStatus, errorThrown) {
    console.error('狀態:', textStatus, '錯誤:', errorThrown);
    // textStatus: 'timeout', 'error', 'abort', 'parsererror'
  },
  
  // 發送前(可返回 false 取消請求)
  beforeSend: function(jqXHR, settings) {
    jqXHR.setRequestHeader('Authorization', 'Bearer ' + getToken());
    $('#loading').show();
  },
  
  // 完成(成功/失敗都執行)
  complete: function(jqXHR, textStatus) {
    $('#loading').hide();
  }
});

模式二:簡便方法 $.get() / $.getJSON() / $.post()


// GET 請求,返回 HTML/文本
$.get('/api/list', { page: 1 }, function(html) {
  $('#container').html(html);
});

// GET 請求,自動解析 JSON 返回
$.getJSON('/api/users', { role: 'admin' }, function(users) {
  renderUserList(users);
});

// POST 請求(表單提交常用)
$.post('/api/login', { username: 'admin', password: '123456' }, function(res) {
  if (res.success) location.href = '/dashboard';
}, 'json'); // 第4參數指定 dataType

優點:代碼極簡。缺點:無法設置 headers、timeout、beforeSend、error 处理有限、難以複用配置。

模式三:表單序列化提交(標準表單 AJAX 化)


$('form.ajax-form').on('submit', function(e) {
  e.preventDefault(); // 阻止默認提交
  
  const $form = $(this);
  const formData = $form.serialize(); // 關鍵:自動序列化為 "a=1&b=2" 字串
  // 或 FormData(支援文件上傳):new FormData(this)
  
  $.ajax($form.attr('action'), {
    type: $form.attr('method') || 'POST',
    data: formData,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded', // serialize() 默認類型
    // contentType: false, processData: false, // 若用 FormData 上傳文件必須加這兩行
    success: function(res) {
      showToast(res.message);
      if (res.redirect) location.href = res.redirect;
    },
    error: function(xhr) {
      showToast('提交失敗: ' + (xhr.responseJSON?.message || xhr.statusText));
    },
    beforeSend: function() {
      $form.find('button[type=submit]').prop('disabled', true).text('提交中...');
    },
    complete: function() {
      $form.find('button[type=submit]').prop('disabled', false).text('提交');
    },
    timeout: 10000
  });
});

進階技巧與最佳實踐

1. 全局默認配置 $.ajaxSetup()


$.ajaxSetup({
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  timeout: 10000,
  cache: false, // GET 請求自動加時間戳防緩存
  xhrFields: { withCredentials: true } // 跨域攜帶 Cookie
});
// 之後所有 $.ajax/get/post 繼承以上配置

2. 全局事件監聽(Loading、錯誤統一處理)


$(document)
  .ajaxStart(() => $('#global-loading').show())
  .ajaxStop(() => $('#global-loading').hide())
  .ajaxError((e, jqXHR, settings, err) => {
    if (jqXHR.status === 401) location.href = '/login';
    else if (jqXHR.status >= 500) showToast('服務器錯誤,請稍後重試');
  });

3. 防重複提交:標記 + 队列


$.ajax({
  url: '/api/action',
  beforeSend: function(jqXHR) {
    if (jqXHR._aborted) return false; // 自定義標記
    jqXHR._aborted = true;
  },
  complete: function(jqXHR) {
    jqXHR._aborted = false;
  }
});

4. 文件上傳(FormData + progress)


$('#file-form').on('submit', function(e) {
  e.preventDefault();
  const formData = new FormData(this);
  
  $.ajax('/api/upload', {
    type: 'POST',
    data: formData,
    contentType: false,  // 關鍵:讓瀏覽器自動設置 multipart/form-data 含 boundary
    processData: false,  // 關鍵:阻止 jQuery 序列化 FormData
    xhr: function() {
      const xhr = new window.XMLHttpRequest();
      xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
          $('#progress').val((e.loaded / e.total * 100).toFixed(0));
        }
      });
      return xhr;
    },
    success: res => console.log('上傳成功', res)
  });
});

5. Promise 化與 async/await(jQuery 3.0+)


async function fetchUser(id) {
  try {
    const user = await $.getJSON(`/api/users/${id}`);
    return user;
  } catch (err) {
    if (err.status === 404) throw new Error('用戶不存在');
    throw new Error('網絡錯誤');
  }
}

常見坑點速查

現象原因解決
POST 參數後端收不到 contentType: 'application/json' 但數據是對象,非 JSON 字串 發送 JSON 時:data: JSON.stringify(obj), contentType: 'application/json'
跨域失敗 無 CORS 頭、或憑證模式不匹配 服務端配置 CORS;前端 xhrFields: {withCredentials:true} 需服務端 Access-Control-Allow-Credentials: true
緩存導致數據不更新 GET 請求被瀏覽器/CDN 緩存 cache: false 或 URL 加時間戳 ?_=${Date.now()}
中文參數亂碼 編碼不一致 確保頁面 <meta charset="utf-8">,後端統一 UTF-8
大文件上傳超時/失敗 默認 timeout 過短、nginx client_max_body_size 限制 調大 timeout、配置 nginx、分片上傳

總結

  • $.ajax():完全控制,複雜場景首選。
  • $.get()/$.post()/$.getJSON():簡單場景快速開發。
  • 表單序列化 .serialize() + $.ajax():標準表單 AJAX 化最佳實踐。
  • 全局配置 + 全局事件:統一認證、Loading、錯誤處理、防重。
  • 現代項目建議遷移至 fetch/axios:原生 Promise、TypeScript 支持、攔截器、取消請求、更輕量。
copyright © 萬盛學電腦網 all rights reserved