php - jQuery preventDefault() 在 AJAX 调用中不起作用

标签 php jquery ajax preventdefault

所以,当用户输入电子邮件时,我会检查该电子邮件是否存在。

 $('form.recover-form#check-form').on('submit', function(e){

    var form    = $(this),
        input   = $('.check-recover-email'),
        span    = $('.recover-error'),
        email   = input.val();
    span.text('');
    e.preventDefault();
    $.ajax({
        url: 'ajax/check-email',
        async: 'false',
        cache: 'false',
        type: 'POST',
        data: {email: email},
        success: function(response) {
            if ( response == 'no' ) {
                span.text('email does not exist');
            } else if ( response == 'ok' ) {
                form.submit();
            }
        }
    });
});

php代码

if ( Input::isPost('email') )  {

    $email = Input::post('email');

    $check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
    $check->execute(array( 'email' => $email ));

    echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;

}

一旦我提交表单,它就会以这种方式提交,并且 AJAX 调用中的 e.PreventDefault() 不起作用。但是,如果我在 AJAX 调用之前放置 e.PreventDefault(),则表单不会提交,如果电子邮件不存在,则会出现错误(这是我想要实现的)。

我不明白问题出在哪里,希望你能帮忙。

谢谢。

EIDT:这是更新后的代码

最佳答案

问题是您在处理事件期间没有调用 preventDefault。相反,在事件处理期间,您开始 ajax 调用(异步),然后让事件继续。 ajax 调用稍后完成,这已经太晚了,无法阻止事件的默认——它已经发生了。

e.preventDefault() 直接移动到事件处理程序中,在 ajax success 处理程序之外。

$('.recover-form').on('submit', function(e){
    var form    = $(this),
        input   = $('.check-recover-email'),
        span    = $('.recover-error'),
        email   = input.val();
    span.text('');
    e.preventDefault(); // <=================== Here
    $.ajax({
        url: 'ajax/check-email',
        async: 'false',
        cache: 'false',
        type: 'POST',
        data: form.serialize(),
        success: function(response){
            if ( response == 0 ) {
                // ============================ Not here, this would be too late
                span.text('email does not exist');
            }
        }
    });
});

在评论中,您说:

Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.

您不能等待异步 ajax 调用的结果来等待原始表单提交。您要做的是取消原始表单提交,执行 ajax,然后如果结果没问题,使用原始 DOM form 上的 submit 方法重新提交表单> 元素。该方法不会重新触发 submit 事件处理程序。

示例:Live copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
  <form action="http://www.google.com/search" method="GET">
    <input type="text" name="q" value="kittens">
    <input type="submit" value="Submit">
  </form>
  <script>
    (function() {
      $("form").submit(function(e) {
        var rawFormElement = this; // Remember the DOM element for the form

        // Stop form submission
        display("Got form submit event, simulating ajax");
        e.preventDefault();

        // Simulate ajax check of data
        setTimeout(function() {
          // (This is the 'success' callback for the ajax)
          display("Ajax call complete, pretending result is good and submitting");

          // All okay, go ahead and submit the form
          rawFormElement.submit(); // Doesn't trigger 'submit' handler
        }, 1500);
      });

      function display(msg) {
        $("<p>").html(String(msg)).appendTo(document.body);
      }
    })();
  </script>
</body>
</html>

关于php - jQuery preventDefault() 在 AJAX 调用中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763746/

相关文章:

php - 更新数据库而不刷新

jquery - AJAX 使用 CORS 获取自定义响应 header

php - 将 HTML 标记存储在 PHP 字符串中

php composer - 我的带有命名空间和类的包

php - xp及练级系统PHP MYSQL

php - 如何在一个查询中执行插入操作?

javascript - 刷新后保持下拉选择

jQuery : mouseover open a lightbox but mouseout can't close it correctly

asp.net - 来自 javascript PageMethods 的自定义 C# 数据传输对象

javascript - 如何在 Django 和 AJAX 中正确显示 ValidationError?