function request(ops) {
// 1.处理参数:可选参数要有默认值,可选函数须先判断
let { url, success, type = "get", data = {}, error, timeout = 1000, dataType = "text", filedName = "" } = ops;
//4.处理数据
let str = '';
for (var i in data) {
str += `${i}=${data[i]}&`;
}
//5.根据请求方式拼接url
if (type !== "post") {
url = url + "?" + str + "_qft_=" + Date.now();
}
//2.判断开启ajax
let xhr;
if (type !== "jsonp") {
//3.创建xhr对象
xhr = new XMLHttpRequest();
//设置请求
xhr.open(type, url);
//6.开启监听
xhr.onload = function() {
if (xhr.status == 200) { //成功
const res = dataType === "json" ? JSON.parse(xhr.responseText) : xhr.responseText;
//ajax的成功:成功后不能失败,也不能再次成功
success && success(res);
error = null;
success = null;
} else { //失败
//ajax的失败
error && error(xhr.status);
success = null;
error = null;
}
}
//8.根据get或者post执行send
if (type == "get") {
xhr.send();
} else {
xhr.setRequestHeader("Content-Type", "application/x-www-urlencoded")
xhr.send(str.slice(0, str.length - 1));
}
} else {
//9.jsonp请求:动态创建script
let script = document.createElement("script");
script.id = "abc";
script.src = url;
document.body.appendChild(script);
//10.声明全局变量:在局部声明全局
window[data[filedName]] = function(res) {
res = dataType === "json" ? JSON.parse(res) : res;
//11.jsonp的成功
success && success(res);
//15.1jsonp请求成功后删除 script标签
script && script.remove();
error = null;
success = null;
}
}
setTimeout(() => {
// 12.超时
// jsonp没有状态可以判断,只能按照超时报错
error && error("timeout");
const s = document.getElementById("abc");
s && s.remove();
success = null;
error = null;
}, timeout)
}
2021-07-11 ajax的三个函数封装:get,post,jsonp
最新推荐文章于 2023-04-14 21:36:33 发布