一、在同级文件夹中新建 ajax.js 文件
1、写入 ajax 请求封装代码
const baseURL = 'http://127.0.0.1';
function ajaxGetList(obj) {
let arrList = [];
for (let key in obj.data) {
arrList.push(key + '=' + obj.data[key])
}
let str = arrList.join('&')
let xhr = new XMLHttpRequest();
let method = obj.type.toUpperCase();
if (method === 'GET' || method === 'DELETE') {
if (str) {
xhr.open(method, baseURL + obj.url + '?' + str, true)
} else {
xhr.open(method, baseURL + obj.url, true)
}
xhr.send()
} else if (method === 'POST' || method === 'PUT') {
xhr.open(method, baseURL + obj.url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
xhr.send(str);
}
xhr.onload = function() {
obj.success(JSON.parse(xhr.responseText));
}
}
二、调用封装好的方法
1、引入页面
<script src="./ajax.js"></script>
2、调用封装好的 ajax 函数
ajaxGetList({
type: 'GET',
url: '/dataList',
data: {
name: 'zhangsan',
age: 21
},
success: function(res) {
console.log(res)
}
})