Ajax的方法和使用代码
1 //1.创建Ajax对象,已经封装好的函数: 2 function createXHR(){ 3 if (typeof XMLHttpRequest != "undefined"){ 4 return new XMLHttpRequest(); 5 } else if (typeof ActiveXObject != "undefined"){ 6 if (typeof arguments.callee.activeXString != "string"){ 7 var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", 8 "MSXML2.XMLHttp"], 9 i, len; 10 11 for (i=0,len=versions.length; i < len; i++){ 12 try { 13 var xhr = new ActiveXObject(versions[i]); 14 arguments.callee.activeXString = versions[i]; 15 return xhr; 16 } catch (ex){ 17 //skip 18 } 19 } 20 } 21 22 return new ActiveXObject(arguments.callee.activeXString); 23 } else { 24 throw new Error("No XHR object available."); 25 } 26 } 27 28 //直接引用 29 30 var xhr = createXHR(); 31 32 //2.请求状态监控 33 34 xhr.onreadystatechange = function(event){ 35 if (xhr.readyState == 4){ 36 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ 37 alert(xhr.responseText); 38 } else { 39 alert("Request was unsuccessful: " + xhr.status); 40 } 41 } 42 }; 43 //3.连接服务器(方法,文件名,异步传输) 44 xhr.open("get", "example.txt", true); 45 //4.发送请求 46 xhr.send(null);
一直在追赶,从未敢怠慢!