Ajax 原生封裝 直接使用
function ajaxMy(options) {
let {
url,
type,
data,
dataType,
success,
fail,
} = options;
// 處理參數
type = type.toUpperCase();
dataType = dataType ? dataType : 'json';
let xhr = null;
// 1. 創建 xhr 對象
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else { //IE6及其以下版本瀏覽器
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// 2. 初始化 並 發送請求
if (type === 'GET') {
// 處理 get 方式的 請求參數
let requestParams = '?';
for (let [key, value] of Object.entries(data)) {
requestParams += `${key}=${value}&`;
}
requestParams = requestParams.slice(0, -1);
xhr.open('GET', url + requestParams);
xhr.send(null);
} else if (type === 'POST') {
// 將請求數據 放到 請求主體中,並沒有發送
xhr.open("POST", options.url, true);
//設置表單提交時的內容類型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 發送請求
xhr.send(data);
}
// 3. 監聽
xhr.onreadystatechange = () => {
if (xhr.readyState ===4) {
if (xhr.status >= 200 && xhr.status < 300) {
success && success(JSON.parse(xhr.responseText));
} else {
fail && fail(xhr.status)
}
}
}
}
Ajax 調用
ajaxMy({
url: 'http://localhost:8011/api/mdm.MaterialBean/addDictItem',
type: 'POST',
data: {
parentId: '',
name: '',
code: '',
desc: ''},
dataType: 'json',
success: (response) => {
console.log(response)
}
})
有什麼不懂,歡迎大家評論區留言