粗心害死人啊,我的天。
1 <script type="text/javascript"> 2 var xhr; 3 4 //创建XMLHttpRequest的函数 5 function createXMLHttpRequest(){ 6 if(window.XMLHttpRequest){ 7 //非IE内核的浏览器 8 xhr=new XMLHttpRequest(); 9 }else{ 10 try { 11 //IE浏览器 12 xhr=new ActiveXObject("Msxml2.XMLHTTP"); 13 } catch (e) { 14 //IE低版本 15 xhr=new ActiveXObject("Microsoft.XMLHTTP"); 16 } 17 } 18 } 19 20 /** 21 *发送请求,用来校验用户名是否重复 22 */ 23 function chkUserName(){ 24 //1、创建XMLHttpRequest对象 25 createXMLHttpRequest(); 26 27 //2、获得用户名 28 var username=document.getElementById("username").value; 29 //3、与服务器建立连接 30 var url="register"; 31 xhr.open("POST",url,true); 32 33 //4、设置回调函数,获得服务器响应的数据 34 xhr.onreadystatechange=function(){ 35 /* 36 readyState:服务器状态响应 37 状态码: 38 0:未初始化 39 1:正在加载 40 2:加载完成 41 3:请求进行中 42 4:请求完成 43 */ 44 45 if(xhr.readyState==4){ 46 //status==200表示响应正常 47 if(xhr.status==200){ 48 var res=xhr.responseText; 49 50 if(res=='0'){ 51 document.getElementById("res").innerHTML="<font color='green'>用户名可以使用</font>"; 52 53 }else{ 54 document.getElementById("res").innerHTML="<font color='red'>用户名已占用</font>"; 55 document.getElementById("username").focus(); 56 } 57 } 58 else{ 59 alert("出现异常"+xhr.response.Text); 60 } 61 62 } 63 } 64 //5发送请求 65 //POST方式 66 //post提交需要设置http请求头 67 68 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 69 xhr.send("username="+username); 70 } 71 </script>
(上述代码是改过后正确的)今天在用ajax的时候!出现了愚蠢的错误!由于括号太多加上自己又粗心了!把最后的第68行的发送请求写到了第63行的大括号里变了~!导致我找了快一个小时的错误了!!!!!!泪奔o(>_<)o ~~发现这个错误后我“北京瘫”了十分钟o(>_<)o ~~