本人纯小白,自己仿jQuery封装了Ajax请求,欢迎大佬来指点!
(function () {
/*
我们规定传递的是一个对象参数如下:
url: 请求地址
type:请求类型
data:参数
success: 回调函数
*/
var $ = {
//get请求封装
get: function (option) {
option.data = this.convertData(option.data)
//创建Ajax对象
var xhr = new XMLHttpRequest();
xhr.open(option.type, option.url + '?' + option.data);
xhr.send();
//监听请求状态改变事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
option.success(result)
}
}
},
//post请求封装
post: function (option) {
option.data = this.convertData(option.data);
//创建Ajax对象
var xhr = new XMLHttpRequest();
xhr.open(option.type, option.url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(option.data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
option.success(result)
}
}
},
//Ajax请求封装
ajax: function (option) {
if (option.type.toUpperCase() === 'GET') {
this.get(option)
} else {
this.post(option)
}
},
//数据转换
convertData: function (data) {
var arr = [];
for (var key in data) {
arr.push(key + '=' + data[key])
}
return arr.join('&')
}
}
window.$ = $
})()
觉得不错的点个赞吧!