DIV CSS 佈局教程網

jQuery 發送 AJAX 請求的常見寫法彙整
編輯:JQuery特效代碼     

本文彙整了 jQuery 發送 AJAX 請求的幾種常見寫法,涵蓋 $.ajax、$.get/$.getJSON,如表單序列化提交等,方便日常查閱。

寫法一:完整 $.ajax

$.ajax('/ROUTE', {
  type: 'GET',
  data: { param1: 'Hello', param2: 'World' },
  dataType: 'json',
  contentType: 'application/json',
  timeout: 3000,
  success: function(response) { /* 成功回呼 */ },
  error: function(request, errorType, errorMessage) { /* 失敗回呼 */ },
  beforeSend: function() { /* 如 .addClass('is-fetching') */ },
  complete: function() { /* 如 removeClass('is-fetching') */ }
});

寫法二:簡便方法

$.get('/ROUTE', function(response) { /* success (HTML) */ });
$.getJSON('/ROUTE', function(response) { /* success (JSON) */ });

寫法三:序列化表單後提交

$('form').on('submit', function(event) {
  event.preventDefault();
  var formData = $(this).serialize();
  $.ajax($(this).attr('action'), {
    type: $(this).attr('method'),
    data: formData,
    dataType: 'json',
    contentType: 'application/json',
    success: function(response) {},
    error: function(request, errorType, errorMessage) {},
    beforeSend: function() {},
    complete: function() {},
    timeout: 3000
  });
});

其中 serialize() 能把表單資料序列化成查詢字串,省去手動收集欄位的麻煩;搭配 beforeSend 與 complete 還能做出載入狀態的視覺回饋。希望本文對大家的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved