极度郁闷的错误调试——ajax jquery
今天在写一个简单邮件验证的页面时,本来以为二十分钟的事情,却调试了一个半小时,简直郁闷,具体的错误如下:
在页面中,有一段如下的代码:
<td colspan="3"> <a href="" id="a-check-mail" onclick="verifyEmail()"/a></td>
其中,verifyEmail()函数如下:
1 function verifyEmail() 2 { 3 4 ...... 5 6 $.ajax({ 7 type: "POST", 8 url: "verifyemail.php", 9 data: {u_email:u_email}, 10 dataType: "text", 11 success: function(resText){ 12 alert(resText); 13 }, 14 error: function(resText){ 15 alert("hahah" + resText); 16 } 17 }); 18 }
做法的本意在点击超链接的时候,通过verifyEmail函数在后台异步提交验证邮箱。但是出现的错误就是不管在后台怎么测试,ajax返回的都是error的函数,调了好久也没发现原因。在网上乱翻的时候,看到某位仁兄有提到<a>标签的刷新问题,才恍然大悟,发现问题的所在。
原来,在我其上的标签里,href是空的,而不是#,这样就会导致了在提交完ajax部分的代码之后,就会执行跳转,虽然是空的,但仍然有页面的刷新。而异步提交返回来的结果的时间比较长,等结果返回的时候,页面早已刷新了,得到的就是error函数的部分。
解决的办法就是讲href用#填充,如下:
<td colspan="3"> <a href="#" id="a-check-mail" onclick="verifyEmail()"/a></td>