整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
ajax
将原生的Ajax封装为prmise
const ajax = (option) => new Promise((resolve, reject) => {
let xmlhttp, timer
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
if (option.type.toLowerCase() === 'get') {
xmlhttp.open("GET", option.url + '?' + objStr(option.data), true)
xmlhttp.send()
} else if (option.type.toLowerCase() === "post") {
xmlhttp.open("POST", option.url, true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(objStr(option.data))
}
xmlhttp.addEventListener("readystatechange", function () {
if (xmlhttp.readyState === 4) {
clearTimeout(timer)
if (xmlhttp.status >= 200 && xmlhttp.status <= 300) {
resolve(xmlhttp)
} else {
reject(xmlhttp)
}
}
}, false)
if (option.timeout) {
timer = setTimeout(() => {
xmlhttp.abort()
clearTimeout(timer)
}, option.timeout)
}
function objStr(obj) {
if (typeof obj === "string") return obj
obj.t = new Date().getTime()
let temp = []
for (let key in obj) {
temp.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
}
return temp.join("&")
}
})
我之前写过ajax的原始写法这个链接上
有时间可以去这篇看一下。