对原生ajax进行封装,使我们如下所示传递数据过去能被处理,并返回处理结果
myAjax({
url: 'url地址api接口',
type: 'get',//请求方式
timeOut: 1000,//响应超时事件
success: function (res) {//成功执行
console.log(res)
},
fail: function (res) {//失败执行
console.log(res)
}
})
function myAjax(options) {
var xhr = new XMLHttpRequest();//创建一个xml对象实例
var method = options.type.toUpperCase();//将请求方式转换成大写
var arr = [];
for (var i in data) {
var arrlist = i + '=' + data[i]
arr.push(arrlist)
}
var text =arr.join('&');//把数据处理成username:zhangsan&pwd:123456这种格式
xhr.responseType = 'json'//设置响应数据格式
if (method == 'GET' || methods === 'DELETE') {
xhr.open(method, options.url + '?' + text);
xhr.send()
} else if (method == 'POST' || methods == 'PUT') {
xhr.open(method, options.url);
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded")//设置请求头
xhr.send(text);
console.log(text)
}
xhr.timeout = options.timeOut;
xhr.ontimeout = function () {
console.log('请求超时')
}
xhr.onerror = function () {
options.fail('请求失败')
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
options.success(xhr.response);
}
}
}