首先感谢本文作者,虽然都是小BUG,但是不注意还是很发现问题。原文地址:http://www.oseye.net/user/kevin/blog/141
今天表单验证时,出现了一个异常现象,耗去了我不少时间呀。
我的验证方法大致如下:
但条件不满足时前面两个return都能拦住checkform继续向下执行,而ajax里面的return却阻止不了checkform向下执行!
- function checkform(){
- var mail=$.trim($('#mail').val());
- if(mail.length==0){
- alert('请填写邮箱');
- $('#mail').focus();
- return;
- }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(mail)){
- alert('邮箱格式不正确');
- $('#mail').focus();
- return;
- }else{
- $.ajax({
- type:"post",
- dataType:'json',
- async: false,
- data:{ mail:mail},
- url:"/checkmail",
- success: function(res){
- if(!res){
- alert('该邮箱已经被注册了');
- $('#mail').focus();
- return;
- }
- },
- error: function(ex){
- alert(("操作失败,请联系我们。");
- $('#mail').focus();
- return;
- }
- });
- }
- //其他验证.....
- }
起初以为设置的同步请求没起作用,查了好多资料,但都是那样设置的。后来使用firefox调试,设置了断点才发现其实已经是同步了,问题就出现在return上,这里的return确实不能阻止程序继续执行。
原因是这里的return只会renturn其自己的域函数,也就是success或error的回调函数。所以可以使用临时变量下即可:
这个问题虽然只是小问题,道理也很容易明白,可我确实耗费了1个多小时,可谓当局者迷呀!!
- function checkform(){
- var mail=$.trim($('#mail').val());
- if(mail.length==0){
- alert('请填写邮箱');
- $('#mail').focus();
- return;
- }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(mail)){
- alert('邮箱格式不正确');
- $('#mail').focus();
- return;
- }else{
- var validate=true;
- $.ajax({
- type:"post",
- dataType:'json',
- async: false,
- data:{ mail:mail},
- url:"/checkmail",
- success: function(res){
- if(!res){
- alert('该邮箱已经被注册了');
- validate=false;
- }
- },
- error: function(ex){
- alert(("操作失败,请联系我们。");
- validate=false;
- }
- });
- if(!validate){
- $('#mail').focus();
- return;
- }
- }
- //其他验证.....
- }