本文彙整了 jQuery 發送 AJAX 請求的幾種常見寫法,涵蓋 $.ajax、$.get/$.getJSON,如表單序列化提交等,方便日常查閱。
$.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 開發有所幫助。