function ajax(options){
var defaults = {
url: '',
type: 'POST',
data: {},
username: '',
password: '',
success: function(){},
error: function(){}
},
opts = this.mergeObject(defaults, options),
xhr = this.getXhrObj();//创建ajax对象
xhr.onreadystatechange = function() {//接收请求
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status >= 200 && xhr.status <= 299){
try{
opts.success.call(xhr, JSON.parse(xhr.responseText));
}catch(error){
opts.success.call(xhr, xhr.responseText);
}
}else {
opts.error.call(xhr);
}
}
};
xhr.onerror = opts.error;
switch(opts.type){
case 'get':
xhr.open(opts.type, opts.url, true);//连接服务器
xhr.send();//发送请求
break;
case 'delete':
opts.url += '?' + this.serializeParam(opts.data);
xhr.open(opts.type, opts.url, true);//连接服务器 xhr.send();//发送请求
break;
case 'post':
xhr.open(opts.type, opts.url, true);
var param = this.serializeParam(opts.data);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(param);
break;
}
return xhr;
}