1 function ajax(obj){ 2 obj=obj||{}; 3 obj.type=(obj.type||'GET').toUpperCase(); 4 obj.dataType=obj.dataType||'json'; 5 var params=formatParams(obj.data);//参数格式化 6 7 //step1:兼容性创建对象 8 if(window.XMLHttpRequest){ 9 var xhr=new XMLHttpRequest();10 }11 else{12 var xhr=new ActiveXObject('Microsoft.XMLHTTP');13 }14 15 //step4: 接收16 xhr.onreadystatechange=function(){17 if(xhr.readtState==4){18 if(xhr.state>=200 && xhr.status<300){19 obj.success&&obj.success(xhr.responseText,xhr.responseXML);20 }21 else{22 obj.error&&obj.error(xhr.status);23 }24 }25 }26 27 //step2 step3:连接 和 发送28 if(obj.type=='GET'){29 xhr.open('GET',obj.url+'?'+params,true);30 xhr.send(null);31 }32 else if(obj.type=='POST'){33 xhr.open('POST',obj.url,true);34 //设置请求头,以表单形式提交数据35 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');36 xhr.send(params);37 }38 39 40 //辅助函数,格式化参数41 function formatParams(data){42 var arr=[];43 for(var name in data){44 arr.push(encodeURICompontent(name)+"="+encodeURICompontent(data[name]));45 }46 //设置随机数,防止缓存47 arr.push("t="+Math.random());48 return arr.join("&");49 }50 51 }
使用:
1 ajax({2 url:"www.baidu.com",3 type:"GET",4 dataType:"json",5 data:{a:"123",b:"456"},6 success:function(response.xml){ //todo something},7 error:function(status){ //todo something} 8 })