AJAX封装

  1. 简单封装

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);
        }
    }
}
}
  1. 对象封装

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)
    }
}
}
}
  1. 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)
}
}
}
})

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值