function ajax(obj) {
let xhr = new XMLHttpRequest()
if (obj.type.toLowerCase() === 'get') {
obj.url += '?rand' + Date.now() + '&'
obj.url += serialize(obj.data)
}
xhr.open(obj.type, obj.url)
if (obj.type.toLowerCase() === 'post') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize(obj.data))
} else {
xhr.send()
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
obj.success(xhr.responseText)
} else {
obj.error('出错了,错误状态是' + xhr.status)
}
}
}
}
function serialize(param) {
var arr = []
for (var key in param){
arr.push(key + '=' + encodeURIComponent(param[key]))
}
return arr.join('&')
}
AJAX的封装
最新推荐文章于 2024-06-07 16:28:20 发布