在jQuery上使用多个远程ajax

时间:2018-08-04 14:35:47

标签: php jquery

我想使用jQuery在电子邮件上进行验证

使用Ajax进行常规验证(必需)和其他验证

第一个用于验证电子邮件是否存在而另一个要验证的功能不在黑名单(其他表格)中

$('#form').validate({
  errorElement: 'span',
  rules:{                
     Email: {
        required: true,
        email: true,
        remote: '/ifexist'
       }
     },
     messages:{
        Email:{
            remote:'email already exist'
          }
        }
   }); 

我尝试添加其他这样的遥控器,但这不起作用

remote: '/ifexist'
remote: '/inblacklist'

我的php代码

if(isset($_GET['Email'])){
   $is_valid = Member::inblacklist($email);
   header('Content-Type: application/json');
   echo json_encode($is_valid);
 }else{}

任何解决方案吗?

1 个答案:

答案 0 :(得分:0)

This answerthis question 声称 jQuery验证插件不支持多个遥控器(我没有看到任何可靠的证据来证明既没有索赔,也没有)。如果要处理您的案件,我会做以下事情。

$('#form').validate({
    errorElement: 'span',
    rules:{                
        Email: {
            required: true,
            email: true,
            remote: {
                url:'/ifexist',
                type:'POST', //Or whatever
                data:function(){
                    return $("#email").val(); // The value of the email field
                },
                dataType:"JSON", // So that you can return a JSON object from the backend
                dataFilter:function(responseData){ // Handles the response
                    /* Assume you return a JSON object as follows
                     * {"isValid":false, "reason":"blacklisted"}
                     * or may be
                     * {"isValid":false, "reason":"duplicate"}
                     */
                    alert(responseData.reason); // Or whatever
                    return responseData.isValid; // validation result
                }
            }
        }
    },
    // Rest of the validation logic

这里发生的是,您可以控制后端验证例程的响应,并根据需要进行处理。

该插件几乎可以完全自定义。有关更多详细信息,请参见documentation

编辑(对原始问题的更新后)

php的后端可能如下。

if(isset($_POST['Email'])){
    $email = $_POST['Email'];
    $response = null;
    $isInBlackList = Member::inblacklist($email);
    if($isBlackList){
        // User is in the blacklist
        $response = array("isValid"=>false, "message"=>"This email is blacklisted!"); // Initialize $response
    }
    else{
        $alreadyExists = Member::alreadyExists($email); // You have to implement this.
        if($alreadyExists){
            // Email already exists
            $response = array("isValid"=>false, "message"=>"This email is already in user"); // Initialize $response
        }
        else{
            // We found a valid email
            $response = array("isValid"=>true);
        }
    }
    header('Content-Type: application/json');
    echo json_encode($response);
}else{}

请注意使用php array()封装响应并将其返回为JSON。

相关问题