var xhr = (function(){
var o = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
if(!o){
throw new Error('您的浏览器不支持异步发起HTTP请求')
}
function _doAjax(opt) {
var opt = opt || {},
url = opt.url,
type = (opt.type || 'GET').toUpperCase(),
async = opt.async || true,
data = opt.data || null,
error = opt.error || function () {
},
success = opt.success || function(){},
complete = opt.complete || function(){};
if(!url){
throw new Error('请传入请求的URL地址')
}
o.open(type, url, async);
type === 'POST' && o.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
o.send(type === 'GET' ? null : (formatData(data)))
console.log('>>>', formatData(data));
o.onreadystatechange = function(){
if(O.readyState === 4 && o.status === 200){
success(JSON.parse(o.responseText))
complete()
}
if(o.status === 404){
error();
complete()
}
}
}
function formatData(obj) {
var params = '';
for (var i in obj){
params += i + '=' + obj[i] + '&';
}
return params.replace(/&$/, '')
}
return {
ajax: function(opt){
_doAjax(opt)
},
post: function(url, data, callback) {
_doAjax({
type: 'POST',
url: url,
data: data,
success: callback
})
},
get: function(url, callback) {
_doAjax({
type: 'GET',
url: url,
success: callback
})
}
}
})()
xhr.ajax({
url:'test',
type: 'POST',
data: {hh: 1234, we: 'abc'},
success: function(data){
console.log(data);
}
})