【问题标题】:Jquery real time input validation with $.post function使用 $.post 函数进行 Jquery 实时输入验证
【发布时间】:2023-03-16 00:12:01
【问题描述】:

大家好:
我是 Jquery 和 Web 开发的新手,所以请多多包涵。 我想在我的网站上使用 Jquery 实现实时输入验证。也许我在这篇文章中有一些语法错误,但我确信我的真实代码中没有任何语法错误。

这就是我所拥有的,每当用户输入非空白的内容时,都会调用 error() 并向服务器(PHP+MySQL)发出 post 请求以检查输入值是否已经存在。按下提交按钮时也会再次使用 error() 。

在我按下提交按钮之前,这工作得很好。如果我输入已经存在的内容,则不会提交表单。但是如果我输入一些新的东西,即使数据仍然被插入到数据库中,我仍然会得到(“exists”)文本。我总是会在(“成功”)之后得到(“存在”)。似乎当我提交时,来自 error() 的 .post 请求是在表单的 .post 请求之后发出的。有人如何解决这个错误?或另一种方式来构建这种类型的输入验证? 谢谢

$('.unique').change(function(){
    error($(this));
});

function error(obj)
{
    var ok = true;

    if(obj.val().length == 0)
    {
        alert('This field can not be blank');
        ok = false;
    }

    else
    {
        var data = "action=check&input=" + obj.attr('name') + "&value=" + obj.val();
        $.post('database.php',
               data,
               function(reply){
                   if(reply == true)
                   {
                      alert("This " + obj.attr('name') + " already exists");
                      ok = false; 
                   }        
               });

    }
    return ok;
}

//When the user submits the form
$('#info').submit(function(){
    var ok = true;
    var data = 'action=insert&' + $(this).serialize();

    //Passes each input to the error()
    $('.unique').each(function{
       var temp = error($(this));
       ok = ok && temp;
    });

    if(!ok) return false;

    $.post('database.php',
           data,
           function(reply){
               alert(reply);
           });
});

<form id="info" name="info" action="" method="post">
   <input type ="text" class = "unique" id = "username" name = "username" class = "unique">
   <input type ="text" class = "unique" id = "email"    name = "email"    class = "unique">
</form>

//On the server
if(isset($_POST['action']))
{
    if($_POST['action'] == 'check')
    { 
        $query = sprintf("select * from Users where %s = '%s'", 
                                                                $_POST['input'],
                                                                $_POST['value']);
        $result = mysql_query($query);
        if(mysql_num_rows($result) > 0)
        { echo true;}

        else
        { echo false;}
    }
    else
    {
        $query = sprintf("insert into Users(username, email) values('%s','%s')", 
                    $_POST['username'],
                    $_POST['email']);
        if(!($result = mysql_query($query)))
            die(mysql_error());

        echo 'Success';
    }      
} 

【问题讨论】:

  • 你能编辑你的帖子并包含 err() 函数吗,从我收集到的时间问题与验证期间发布的每个帖子的结果有关,你想等待每个帖子完成之前尝试插入操作
  • 嗨 Almog 我确实在帖子中包含了 error(),谢谢
  • i ment 这一行 => var temp = err($(this));它实际上是 var temp = error($(this)); ??
  • 其实是错误($(this)),我刚刚编辑了,谢谢

标签: php javascript jquery


【解决方案1】:

我过去也遇到过这个问题。您可以避免这种情况以防止默认行为:

$('#info').submit(function(e){
e.preventDefault();

var ok = true;
var data = 'action=insert&' + $(this).serialize();

//Passes each input to the error()
$('.unique').each(function{
   var temp = err($(this));
   ok = ok && temp;
});

if(!ok) return false;

$.post('database.php',
       data,
       function(reply){
           alert(reply);
       });
});

这将避免实际提交表单。如果你还想在ajax post没问题的时候提交:

$('#info').submit(function(){
  var theForm = this;
  $.post('database.php',
       data,
       function(reply){
           alert(reply);
           theForm.submit();
       });
});

【讨论】:

    【解决方案2】:

    有几个问题立即突出。 第一个错误函数总是返回 false。 第二个 $.post 是异步的。这意味着它将在等待来自 ajax 请求的响应时继续执行代码。您可以在 $.post 请求之前使用 $.ajaxSetup({async:false}); 在 jquery 中更改它。

    这是一个应该可以正常工作的代码示例:

    $('.unique').change(function(){
        error($(this));
    });
    
    function error(obj)
    {
        var ok = true;
    
        if(obj.val().length == 0)
        {
            alert('This field can not be blank');
            ok = false;
        }
        else
        {
            var data = {
              action: 'check',
              input: obj.attr('name'),
              value: obj.val()
            };
    
            $.ajaxSetup({async:false}); // Force program execution to wait for ajax response 
            $.post('database.php', data, function (reply) {
              if (reply) {
                alert("This " + obj.attr('name') + " already exists");
                ok = false;
              }
              $.ajaxSetup({async:true}); // Setup ajax to be async again
            });
        }
        return ok;
    }
    
    //When the user submits the form
    $('#info').live('submit', function(e){
        e.preventDefault();
        var ok = true;
    
        //Passes each input to the error()
        $('.unique').each(function(){
           ok = ok && error($(this));
        });
    
        if (!ok) { 
          return false;
        }
    
        $.post('database.php', 'action=insert&' + $(this).serialize(), function(r) {
          alert(reply);
        });
    });
    

    【讨论】:

    • 是的,关于这篇文章中错误的 ok 变量,我刚刚修复了它,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多