还比较好用
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)
}
}
}
}
用法
ajaxMy({
url: 'http://localhost:8011/api/mdm.MaterialBean/addDictItem',
type: 'POST',
data: {
parentId: '',
name: '',
code: '',
desc: ''},
dataType: 'json',
success: (response) => {
console.log(response)
}
})
评论(5)
nihao
buga
bfgg
前端一枚,最近买了阿里云服务器,正在研究,看到您的博客,很详细,感谢!另外我想问一下,您这个代码片段排版使用的是什么库!
mditor 插件,支持markdown 语法,代码排版应该是内置的。