function resolveDate (obj) {
var arr = []
for (let k in obj) {
arr.push(k + '=' + obj[k])
}
// 返回一个以&分隔的字符串
return arr.join('&')
}
function myAjax (options) {
var xhr = new XMLHttpRequest()
// 将传来的参数对象转换为查询字符串
var query = resolveDate(options.data)
if (options.method.toUpperCase() === 'GET') {
// 发起get请求
xhr.open('GET', options.url + '?' + query)
xhr.send()
} else if (options.method.toUpperCase() === 'POST') {
xhr.open('POST', options.url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(query)
}
// 监听
xhr.onreadystatechange = function () {
if ( xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
options.success(result)
}
}
}
封装一个简单的Ajax
最新推荐文章于 2024-04-07 02:00:47 发布