1 /* 2 * 统一XHR接口 3 */ 4 function createXHR() { 5 // IE7+,Firefox, Opera, Chrome ,Safari 6 if(typeof XMLHttpRequest != "undefined") { 7 return new XMLHttpRequest(); 8 } 9 // IE6- 10 else if(typeof ActiveXObject != "undefined"){ 11 if(typeof arguments.callee.activeXString != "string") { 12 var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXMLHttp"], 13 i, len; 14 for(i = 0, len = versions.length; i < len; i++) { 15 try{ 16 new ActiveXObject(versions[i]); 17 arguments.callee.activeXString = versions[i]; 18 break; 19 }catch(ex) { 20 alert("请升级浏览器版本"); 21 } 22 } 23 } 24 return arguments.callee.activeXString; 25 }else { 26 throw new Error("XHR对象不可用"); 27 } 28 } 29 30 var xhr = createXHR(); 31 // 定义xhr对象的请求响应事件 32 xhr.onreadystatechange = function() { 33 switch(xhr.readyState) { 34 case 0 : 35 //alert("请求未初始化"); 36 break; 37 case 1 : 38 //alert("请求启动,尚未发送"); 39 break; 40 case 2 : 41 //alert("请求发送,尚未得到响应"); 42 break; 43 case 3 : 44 //alert("请求开始响应,收到部分数据"); 45 break; 46 case 4 : 47 alert("请求响应完成得到全部数据"); 48 if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { 49 var data = xhr.responseText; 50 alert(data); 51 }else { 52 alert("Request was unsuccessful : " + xhr.status + " " + xhr.statusText); 53 } 54 break; 55 } 56 }; 57 /* 58 // get请求 59 // get请求添加查询参数 60 function urlParam(url, name, value) { 61 url += (url.indexOf(‘?‘) == -1 ) ? ‘?‘ : ‘&‘ ; 62 url += encodeURIComponent(name) + "=" + encodeURIComponent(value); 63 return url; 64 } 65 66 // get请求 67 url = urlParam("example.php","name","ccb"); 68 url = urlParam(url,"pass","123"); 69 xhr.open("get", url ,true); 70 xhr.send(null);*/ 71 72 // post请求 73 // 格式化post 传递的数据 74 function postDataFormat(obj){ 75 if(typeof obj != "object" ) { 76 alert("输入的参数必须是对象"); 77 return; 78 } 79 80 // 支持有FormData的浏览器(Firefox 4+ , Safari 5+, Chrome和Android 3+版的Webkit) 81 if(typeof FormData == "function") { 82 var data = new FormData(); 83 for(var attr in obj) { 84 data.append(attr,obj[attr]); 85 } 86 return data; 87 }else { 88 // 不支持FormData的浏览器的处理 89 var arr = new Array(); 90 var i = 0; 91 for(var attr in obj) { 92 arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]); 93 i++; 94 } 95 return arr.join("&"); 96 } 97 } 98 99 // post请求 100 var data = {name : "ccb" , pass : "123"}; 101 xhr.open("post", "example.php", true); 102 // 不支持FormData的浏览器的处理 103 if(typeof FormData == "undefined") { 104 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 105 } 106 xhr.send(postDataFormat(data));
时间: 2024-10-13 00:15:17