var ajaxTool = {
setting : {
method : 'get',
url : location.href,
data : '',
callback : function(){alert('兄弟,你忘记写回掉函数了吧')}
},
ajax :function(json){
//初始化数据
var This = this
this.extend(this.setting,json);
//创建一个xhr对象
var xhr = new XMLHttpRequest();
//格式化数据格式 以字符串键值队的形式传递数据
this.setting.data = this.format(this.setting.data);
//发送请求
if(this.setting.method == 'get'){
this.setting.url += "?" + this.setting.data
this.setting.data = null;
}
xhr.open(this.setting.method,this.setting.url,true);
if(this.setting.method == 'post'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
}
//发送请求
xhr.send(this.setting.data)
//监听请求状态
xhr.onreadystatechange = function (){
if(xhr.readyState==4&&xhr.status==200){
var result = JSON.stringify(xhr.responseText) //假设请求的是json文件
result = JSON.parse(result);
This.setting.callback(result);
}
}
},
extend :function(obj1,obj2){
for (var attr in obj2) {
obj1[attr] = obj2[attr]
}
},
format : function(data){
var html ="";
for (var attr in data) {
html += attr + '=' + data[attr]+'&';
}
html = html.substring(0,html.length-1)
return html;
}
}