var $={};
$.ajax=ajax //模仿jquery
function ajax(options){
options=options||{};
if(!options.url){
return
}
options.type=options.type||'post'; //方法
options.data=options.data||{}; //内容
options.timer=options.timer||0; //超时时间
var str=jsontourl(options.data) //data内容转换成字符串
//1创建ajax对象 并做兼容
if(XMLHttpRequest){
var xhr=new XMLHttpRequest() //高级浏览器
}else{
var xhr=new ActiveXObject('Microsoft.XMLHTTP') //低级浏览器
}
if(options.type='get'){
//2创建连接
xhr.open('get',options.url+'?'+str,true);
//3发送请求
xhr.send();
}else{
//2创建连接
xhr.open('post',options.url,true);
//设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//3发送请求
xhr.send(str);
}
//4接受请求
xhr.onreadystatechange=function(){ //当页面加载状态改变的时候
//ajax需要判断2个状态 xhr http状态
/*
属性readyState的含义
0 ajax对象创建完成 1 连接建立成功 2 数据发送成功 3 接收数据 报文头 响应头 4 接收数据 报文体 响应体 内容*/
/*
属性status的含义:
0**:未被始化
1**:请求收到,继续处理
2**:操作成功收到,分析、接受
3**:完成此请求必须进一步处理
4**:请求包含一个错误语法或不能完成
5**:服务器执行一个完全有效请求失败
*/
if(xhr.readyState==4){
clearTimeout(timer);
if(xhr.status>=200&&xhr.status<300||xhr.status==304){
options.success&&options.success(xhr.responseText);
}else{
options.error&& options.error(xhr.status)
}
}
}
if(options.timer){
var timer = setTimeout(function(){
alert("超时了!");
xhr.abort();//终止请求
},options.timeout);
}
}
function jsontourl(json){
var arr=[];
json.t=Math.random();
for(var name in json){
arr.push(name+'='+encodeURIComponent(json[name]));
}
return arr.join('&');
}