ajax-util.js(包含統一錯誤處理、Loading、Token 註入等)。
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="/js/ajax-util.js"></script>
// ajax-util.js
var AjaxUtil = (function($) {
function request(options) {
// 合並默認配置
var defaults = {
type: 'POST',
dataType: 'json',
contentType: 'application/json',
beforeSend: function(xhr) { xhr.setRequestHeader('X-Token', getToken()); },
error: function(xhr) { handleError(xhr); }
};
return $.ajax($.extend({}, defaults, options));
}
return { request: request, get: get, post: post }; // 暴露到全局
})(jQuery);
<script>
$(function() {
$('#btnSubmit').click(function() {
var data = { username: $('#user').val(), pwd: $('#pwd').val() };
// 調用封裝好的 post 方法
AjaxUtil.post({
url: '/api/login',
data: JSON.stringify(data),
success: function(res) {
if (res.code === 200) {
window.location.href = '/dashboard';
} else {
alert(res.msg);
}
}
});
});
});
</script>
$/jQuery)。AjaxUtil、HttpClient、api),查看文件末尾 window.Xxx = ... 或 return {}。post/get/request 參數結構(url, data, success, error 等)。contentType: 'application/json' 並 JSON.stringify(data)。
// ajax-util.js (ES Module)
export const request = (options) => { ... };
export const get = (url, params) => ...;
export const post = (url, data) => ...;
// 頁面組件中
import { post } from '@/utils/ajax-util';
post('/api/login', { username, pwd }).then(res => { ... });
「引入順序對、對象名對、方法簽名對」三對齊,現成 AJAX 封裝包即拿即用,勿重複造輪子。