萬盛學電腦網

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

jQuery $.ajax vs $.post 詳解:參數全覽、使用場景、錯誤處理最佳實踐

$.ajax:功能最全、配置最細

$.ajax({
  url: '/api/users',           // 必填
  type: 'POST',                // GET/POST/PUT/DELETE...
  data: { id: 1, name: 'Tom' }, // 對象/字符串/FormData
  dataType: 'json',            // 預期返回類型:json/xml/html/script/text/jsonp
  contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // 發送編碼
  processData: true,           // 是否將 data 轉為查詢字符串(FormData 設 false)
  async: true,                 // true=異步,false=同步(阻塞瀏覽器,慎用)
  timeout: 10000,              // 超時毫秒數
  cache: false,                // GET 請求是否緩存
  headers: { 'X-CSRF-Token': '...' }, // 自定義請求頭
  xhrFields: { withCredentials: true }, // 跨域攜帶 Cookie
  beforeSend: function(xhr) {  // 請求前:可修改 xhr、返回 false 取消
    showLoading();
  },
  success: function(data, textStatus, xhr) { // 成功回調
    render(data);
  },
  error: function(xhr, textStatus, errorThrown) { // 失敗回調
    handleError(xhr, status, error);
  },
  complete: function(xhr, textStatus) { // 完成回調(成功/失敗都執行)
    hideLoading();
  }
});

$.post:POST 專用簡寫

$.post(url, data, successCallback, dataType);
// 等價於
$.ajax({ type: 'POST', url, data, success: successCallback, dataType });

同理:$.get、$.getJSON、$.getScript。

核心參數深度解析

dataType:預期返回類型決定解析方式

值回調參數類型備註
jsonObject/Array自動 JSON.parse,要求響應 Content-Type: application/json
xmlXMLDocument可用 jQuery 選擇器遍歷
htmlString包含 script 標簽會執行
scriptString作為 JS 執行,跨域自動轉 GET
textString純文本
jsonpObject跨域 JSONP,自動處理 callback 參數

data:發送數據的多種形式

// 1. 純對象 -> 自動序列化為 a=1&b=2
{ a: 1, b: 2 }

// 2. 數組對象 -> a=1&a=2
{ a: [1, 2] }

// 3. 字符串 -> 直接發送(需自行編碼)
'a=1&b=2'

// 4. FormData -> multipart/form-data(文件上傳必須)
var fd = new FormData();
fd.append('file', fileInput.files[0]);
fd.append('name', 'test');
$.ajax({ data: fd, processData: false, contentType: false, ... });

// 5. 函數 -> 返回上述任意類型
data: function() { return { timestamp: Date.now() }; }

錯誤處理三參數詳解

error: function(xhr, textStatus, errorThrown) {
  // xhr: jqXHR 對象(包含 responseText, responseJSON, status, getResponseHeader...)
  // textStatus: 'timeout' | 'error' | 'abort' | 'parsererror' | 'notmodified'
  // errorThrown: HTTP 狀態文本(如 'Not Found', 'Internal Server Error')或異常對象

  if (textStatus === 'timeout') { /* 超時重試 */ }
  else if (textStatus === 'parsererror') { /* JSON 解析失敗 */ }
  else if (xhr.status === 401) { /* 未登錄,跳轉登錄頁 */ }
  else if (xhr.status === 403) { /* 無權限 */ }
  else if (xhr.status >= 500) { /* 服務器錯誤 */ }
  else { /* 網絡錯誤、CORS 失敗等 */ }
}

Promise 接口(jQuery 1.5+)

var promise = $.ajax({ url: '/api', dataType: 'json' });

promise.done(function(data) { /* success */ })
       .fail(function(xhr, status, err) { /* error */ })
       .always(function() { /* complete */ });

// 鏈式
$.ajax(...).then(successFn, errorFn).always(completeFn);

// 多請求並行
$.when($.ajax('/api/1'), $.ajax('/api/2')).done(function(res1, res2) {
  // res1[0], res2[0] 為數據
});

常見坑與解決

  1. Content-Type 不匹配:後端返回 JSON 但無 application/json 頭 → parsererror。解決:後端加頭或前端 dataType: 'text' 手動 JSON.parse。
  2. 跨域無 Cookie:需 xhrFields: {withCredentials:true} + 後端 Access-Control-Allow-Credentials: true + Access-Control-Allow-Origin 指定域(不可 *)。
  3. 同步請求卡死頁面:async:false 已棄用,改用 async/await + Promise。
  4. 重複請求:提交前禁用按鈕、用標記變量、或 $.ajaxSetup({cache:false}) 防 GET 緩存。

現代替代:Fetch API + 封裝

async function request(url, options = {}) {
  const res = await fetch(url, {
    method: options.method || 'GET',
    headers: { 'Content-Type': 'application/json', ...options.headers },
    body: options.data ? JSON.stringify(options.data) : undefined,
    credentials: 'same-origin'
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return options.dataType === 'json' ? res.json() : res.text();
}

// 使用
request('/api/user', { method: 'POST', data: {id:1} }).then(render).catch(handleError);

總結

$.ajax 是瑞士軍刀,$.post/get/getJSON 是常用刀具。掌握 dataType、data 序列化、錯誤三參數、Promise 接口、跨域憑證,即可應對 99% 場景。新項目建議漸進遷移至 Fetch + 統一攔截器,代碼更現代、可樹搖、無依賴。

copyright © 萬盛學電腦網 all rights reserved