将对象或数组转化为字符串
function reslovedata(data) {
var arr = []
for (let k in data) {
arr.push(k + '=' + data[k])
}
return arr.join('&')
}
封装Ajax函数
// 定义ajxa请求函数
function ajax(options) {
var xhr = new XMLHttpRequest()
// 将外界传递过来的参数对象,转化为查询字符串
var qs = reslovedata(options.data)
if (options.method.toUpperCase() === 'GET') {
// 发起GET请求
xhr.open(options.method, options.url + '?' + qs)
xhr.send()
} else if (options.method.toUpperCase() === 'POST') {
// 发起POST请求
xhr.open(options.method, options.url)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 & xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
// 执行回调函数
options.success(result)
}
}
}
引用规范
ajax({
method: '方法',
url: '接口',
data:参数对象
success:回调函数
})