1 function TuziAjax(reqType,url,fnoK, fnFail) 2 { 3 var xmlHttp = null; 4 if (window.XMLHttpRequest) { 5 xmlHttp = new XMLHttpRequest(); 6 } 7 else { 8 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//兼容IE6 9 } 10 //连接服务器 open(提交方法,url,是否异步); 11 xmlHttp.open(reqType.toLowerCase()=="post"?"post":"GET", url, true); 12 13 //发送请求 14 xmlHttp.send(); 15 16 //接受返回 17 xmlHttp.onreadystatechange = function () { 18 if (xmlHttp.readyState == 4) { 19 if (xmlHttp.status == 200) { 20 fnoK(xmlHttp.responseText); 21 } 22 else { 23 if (fnFail) {//如果传入请求失败函数,就调用该函数 24 fnFail(); 25 } 26 } 27 } 28 } 29 30 }
使用
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <html> 3 <head> 4 <title>测试</title> 5 <script src="TuziAjax.js" type="text/javascript"></script> 6 <script type="text/javascript"> 7 8 window.onload = function () { 9 var btnAjax = document.getElementById("btnAjax"); 10 btnAjax.onclick = function () { 11 TuziAjax("GET",'txt.txt', function (data) { 12 alert(data); 13 }, function () { alert("请求失败"); }); 14 }; 15 } 16 17 </script> 18 </head> 19 <body> 20 <input type="button" value="测试ajax库" id="btnAjax" /> 21 </body> 22 </html>