简单封装
function ajax(method, url, data, callback) {
var xhr = new XMLHttpRequest()
if (method.toUpperCase() === 'GET') {
// xhr.send()
url = url + "?" + data
}
xhr.open(method, url, true)
if (method.toUpperCase() === 'POST') { xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
xhr.send(data)
} else {
xhr.send()
}
xhr.onload = function () {
//readyState请求的状态
if (xhr.readyState === 4) {
//status服务器响应的状态
if (xhr.status === 200) {
//获取响应的数据
callback && callback(xhr.responseText);
}
}
}
}
对象封装
function ajax(options) {
var xhr = new XMLHttpRequest()
// name='zhangsan'& password=123
var obj = {
type: 'get',
url: './数据.json',
data: {},
"contentType": "application/x-www-form-urlencoded",
success: function (data) {
console.log(data);
},
err: function (data) {
console.log(data);
}
}
obj = Object.assign(obj, options)
var data = ''
for (let key in obj.data) {
data += key + "=" + obj.data[key] + '&'
}
data = data.substr(0, data.length - 1)
if (obj.type.toUpperCase() === 'GET') {
obj.url = obj.url + "?" + data
}
xhr.open(obj.type, obj.url, true)
if (obj.type.toUpperCase() === 'POST') {
var type = obj.contentType
xhr.setRequestHeader('content-type', type)
if (type === 'application/x-www-form-urlencoded') {
xhr.send(data)
} else if (type === 'application/json') {
xhr.send(JSON.stringify(data))
}
xhr.send(data)
} else {
xhr.send()
}
xhr.onload = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
obj.success(xhr.responseText)
}
}
}
}
promise封装
function ajax(method, url, data) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest()
if (method.toUpperCase() === 'GET') {
// xhr.send()
url = url + "?" + data
}
xhr.open(method, url, true)
if (method.toUpperCase() === 'POST') {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send(data)
} else {
xhr.send()
}
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return
} else {
if (xhr.status === 200) {
resolve(xhr.responseText)
// callback && callback(xhr.responseText);
} else {
reject(xhr.status)
}
}
}
})
}