有什么优化的可以一起讨论,本人初级前端一枚
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function configAjax({baseUrl, timeout}) {
// 处理参数的
function objToStr(data) {
data = data || {}
let keys = Object.keys(data)
let str = ""
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const val = data[keys[i]]
str += `&${key}=${val}`
}
str = str.substring(1)
return encodeURIComponent(str)
}
return function ({path = "", data = {}, method = "get"}) {
return new Promise((resolve, reject) => {
let xhr = null
let timerId = null
let params = objToStr(data)
// 兼容性
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest()
} else {// code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 发起请求
if (method.toLowerCase() === "get") {
path += params ? "?" : ""
xhr.open(method, baseUrl + path + params, true);
xhr.send()
} else {
xhr.open(method, baseUrl + path, true)
xhr.send(params)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
clearInterval(timerId)
if (xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304) {
resolve(JSON.parse(xhr.responseText))
} else {
reject("请求异常:" + xhr.status)
}
}
}
if (timeout) {
timerId = setInterval(() => {
xhr.abort()
reject("已超时,中断请求")
}, timeout || 6000)
}
})
}
}
let myAjax = configAjax({
baseUrl: "http://127.0.0.1:3666",
timeout: 10000
})
myAjax({
path: "/api/get",
data: {
name: "晨晨",
age: 66
}
}).then(res => {
console.log(res)
})
</script>
</body>
</html>