const ajax = function (option) {
let init = {
method: 'GET',
url: '',
data: {},
contentType: true, //false时为formdata
success: function () { },
error: function () { }
};
//合并参数
Object.assign(init, option);
init.method = init.method.toLocaleUpperCase();
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
// 启动并发送一个请求
if (init.method == 'GET') {
//参数转换
let params = formatParams(init.data); // init.data请求的数据
xhr.open('get', init.url + '?' + params, true);
xhr.send();
} else if (init.method == 'POST') {
xhr.open('post', init.url, true);
// 设置表单提交时的内容类型
// Content-type数据请求的格式
if (init.contentType) {
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(init.data));
} else {
xhr.send(init.data);
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
let status = xhr.status;
if ((status >= 200 && status < 300) || status == 304) {
init.success && init.success(xhr.response);
} else {
init.error && init.error(status);
}
}
};
};
ajax请求的原生js实现
最新推荐文章于 2024-07-19 12:58:53 发布