jQuery ajax validate部分工作

时间:2011-01-19 08:51:11

标签: javascript jquery validation

这是我的代码:

    $(function() {

        var name = $( "#name" ),
            email = $( "#email" ),
            password = $( "#password" ),
            allFields = $( [] ).add( name ).add( email ).add( password ),
            tips = $( ".validateTips" );

        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }

function ajaxValidate(type,fval,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "type="+type+"&q="+escape(fval.val()),
       success: function(msg){
         if (msg != "") {
         fval.addClass( "ui-state-error" );
         updateTips( n );
             return false;
         }
         else {
             return true;
         }
       }
     });
}

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 540,
            width: 420,
            modal: true,
            buttons: {
                "Create an account": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkLength( name, "username", 3, 16 );
                    bValid = bValid && checkLength( email, "email", 6, 80 );
                    bValid = bValid && checkLength( password, "password", 5, 16 );
                    bValid = bValid && ajaxValidate("user", name,"Username is taken");
                    bValid = bValid && ajaxValidate("email", email,"Email address is taken");


                    bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                    bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                    if ( bValid ) {
                        $( "#users tbody" ).append( "<tr>" +
                            "<td>" + name.val() + "</td>" + 
                            "<td>" + email.val() + "</td>" + 
                            "<td>" + password.val() + "</td>" +
                        "</tr>" ); 

                        document.forms["regform"].submit();
                        $( this ).dialog( "close" );

                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });

        $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });

我的问题在于ajaxValidate函数以及调用该函数的代码中的两行。

由于一些奇怪的原因,它只能运行一次,这意味着,如果您保留第一次验证用户的呼叫,它将正确执行但不会验证电子邮件,但如果您首先放置电子邮件验证呼叫,它会验证它,但不会验证用户。

验证脚本的其余部分可以工作,所以如果我注释掉这两个调用行,那么一切都运行良好。

PHP脚本也可以。

为什么?

更新

好的,我通过统一验证请求稍微更改了函数,所以现在ajaxValidate看起来像这样:

function ajaxValidate(fval1,fval2,n) {
    //alert(type+" "+fval.val()+" "+n);
    $.ajax({
       type: "GET",
       url: "ajaxValidate.php",
       data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
       success: function(msg){
         alert(fval1.val());
         alert(msg);
       }
     });
}

对函数的调用如下所示:

bValid = bValid && ajaxValidate(email, name ,"Email/User address is taken");

ajaxValidate.php看起来像这样:

require_once('classes/db/conn.php');
$user = $_GET['user'];
$email = $_GET['email'];


$query_user = mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Username = '$user'"));

$query_email= mysql_fetch_array(mysql_query("SELECT USR_ID FROM users WHERE USR_Email = '$email'"));


echo("SELECT USR_ID FROM users WHERE USR_Email = " . $email);

现在,在我提交表单后,我应该收到一封警告,其中包含填写的电子邮件,以及一条警报,其中包含ajax响应的内容,该警告应该是来自{{1}的电子邮件的sql查询} var。

我得到的是,在第一个警报时我正确地收到了电子邮件地址,在第二个警报中我得到了整个查询,但是没有电子邮件地址。 ($_GET

我疯了,我想不出来了!

2 个答案:

答案 0 :(得分:0)

您的ajaxValidate函数没有显式返回任何内容,因此它会隐式返回undefined,然后将其转换为布尔值false。

为了能够从函数返回验证状态,您应该对服务器端验证器进行同步调用。查看有关发出ajax请求的jQuery docs,您需要将async属性设置为false。

答案 1 :(得分:0)

我认为问题在于你实际上是在期待一个对象时传递数据键的字符串值。例如。 -

jQuery.ajax({type:“GET”,url:“/”,data:“?bob = bob&amp; carol = carol”,success:function(){console.log(arguments.length);}} )

实际点击网址 - stackoverflow.com / _ = 1295905818376&安培;?BOB =鲍勃&安培;卡罗尔=卡罗尔

然而 -

jQuery.ajax({type:“GET”,url:“/”,data:{bob:“bob”,carol:“carol”},success:function(){console.log(arguments.length) ;}})

点击网址 - stackoverflow.com / _ = 1295906023724&安培; BOB =鲍勃&安培;卡罗尔=卡罗尔

(出现的额外参数是jQuery添加的时间戳,以防止响应被缓存)

因此,我认为如果您将代码更改为以下内容,它应该会为您提供预期的警报 -

 $.ajax({
   type: "GET",
   url: "ajaxValidate.php",
   data: {email: fval1.val()), user:fval2.val()},
   success: function(msg){
     alert(fval1.val());
     alert(msg);
   }
 });

值得注意的是,成功回调函数中的代码将在未来的某个时刻运行,而不是在代码中的那个时刻运行。这意味着您可能不得不将验证代码重新编写为某种形式 -

           "Create an account": function() {
                var bValid = true;
                allFields.removeClass( "ui-state-error" );

                bValid = bValid && checkLength( name, "username", 3, 16 );
                bValid = bValid && checkLength( email, "email", 6, 80 );
                bValid = bValid && checkLength( password, "password", 5, 16 );


                bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. john.doe@pokermaps.org" );
                bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
                var $this = $(this);
                $.ajax({
                  type: "GET",
                  url: "ajaxValidate.php",
                  data: "?email="+escape(fval1.val())+"&user="+escape(fval2.val()),
                  success: function(msg){
                    $( "#users tbody" ).append( "<tr>" +
                        "<td>" + name.val() + "</td>" + 
                        "<td>" + email.val() + "</td>" + 
                        "<td>" + password.val() + "</td>" +
                    "</tr>" ); 

                    document.forms["regform"].submit();
                    $this.dialog( "close" );
                  },
                });
            },

我之前从未使用过对话框,所以我不确定该插件期望函数返回等等,但是你会想要一个更像这样的结构来支持异步调用。 / p>

希望有所帮助,

克里斯