【问题标题】:jQuery prevent submit of form inside of if statementjQuery防止在if语句中提交表单
【发布时间】:2021-03-09 13:56:26
【问题描述】:

对不起,如果有一些错误,但我是一个完全的菜鸟,我也是第一次在 StackOverflow 上发帖。

我正在尝试配置一个提交表单,它控制插入的 PIN 是否正确,如果正确,则继续提交。我做了一些在线研究,发现我们可以使用 jQuery 来运行 event.preventDefault(),我尝试将它插入到我的 AJAX 请求中,但看起来它并没有阻止表单被保存。

代码如下所示:

function verifyOTP() {
    $(".error").html("").hide();
    $(".success").html("").hide();
    var otp = $("#contomovimentato").val();
    var PIN =  $("#PINvalue").val();
    var input = {
        "otp" : otp,
        "PIN" : PIN,
        "action" : "verify_otp"
    };
    if (otp != null) {
        $.ajax({
            url : 'm_ajaxpinr.php',
            type : 'GET',
            dataType : "json",
            data : input,
            success : function(response) {
                $("." + response.type).html(response.message)
                $("." + response.type).show();
                },
            error : function() {
                alert("ss");
            }
        });
    } else {
        $(".error").html('XPIN non valido.')
        $(".error").show();
        error : function(event) { event.preventDefault(); };
    }
 //if I insert "return false;" here the submit is always blocked
}

如果括号是正确的,我检查了 atom,它看起来是正确的。 我应该如何使用 preventDefault() 有什么想法吗? 我还检查了 m_ajaxpinr.php 的输出是否正确,它是正确的。我也试过这样的,但还是不行……

    if (otp != null) {
        $.ajax({
            url : 'm_ajaxpinr.php',
            type : 'GET',
            dataType : "json",
            data : input,
            success : function(response) {
                $("." + response.type).html(response.message)
                $("." + response.type).show();
        $("form").submit(function(event) {
                    if (response.type == 'success')
                {
                    alert(response.type);
                }
                else if (response.type == 'error') 
                {
                    alert(response.type);
                    event.preventDefault();
                }
                });

【问题讨论】:

  • event 没有被传递给你的函数,所以你不能在它上面调用preventDefault()。访问事件的方式取决于调用verifyOTP() 函数的方式。你能把这个逻辑添加到问题中吗?
  • return false 在最后,所以它一直阻塞,然后在success:(验证后)调用$("#your_form_id")[0].submit()提交验证后的表单并绕过jquery 提交处理程序。
  • 问题是 ajax 调用是异步的,所以当你的代码到达最后一行(你的评论)时,ajax 调用仍在运行 - 所以你需要在 ajax 调用完成后“继续” .
  • 我尝试在$("." + response.type).show(); 之后插入“$("'form_id")[0].submit();,但现在表单总是在提交,即使PIN 码错误

标签: javascript jquery preventdefault


【解决方案1】:

正如上面评论所说的ajax调用是异步的,您需要完成表单的取消默认操作或将event.preventDefault();放在顶部功能,然后如果有效otp则在成功功能中提交。

.val() 不会返回null,如果没有输入则返回empty

$('#myForm').on('submit', verifyOTP);

function verifyOTP(e) {
  e.preventDefault(); // note this
  
  $(".error").html("").hide();
  $(".success").html("").hide();
  var otp = $("#contomovimentato").val();
  var PIN = $("#PINvalue").val();
  var input = {
    "otp": otp,
    "PIN": PIN,
    "action": "verify_otp"
  };

  if (otp) { // mean not null, undefined, empty, false, 0
    $.ajax({
      //url: 'm_ajaxpinr.php',
      url: 'https://httpbin.org/anything/test',
      type: 'GET',
      dataType: "json",
      data: input,
      success: function(response) {
        $("." + response.type).html(response.message)
        $("." + response.type).show();
        if(response.args.otp == 1234){
           console.log('valid otp, continue submission')
           $('#myForm').off('submit'); // remove submit event
           $('#myForm').submit(); // then submit the form
        }
        else{
          console.log('invalid pin,\nvalid pin: 1234');
        }
      },
      error: function() {
        console.log("server error, submission cancelled");
      }
    });
  } else {
    $(".error").html('XPIN non valido.')
    $(".error").show();
    console.log("otp maybe empty, submission cancelled");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <input id="contomovimentato">
  <button>submit</button>
</form>

【讨论】:

  • 感谢您的完整回答!真的很好,是的,我有点理解 ajax 是异步的这一事实,但无法意识到如何以“等待”ajax 调用结束的方式更改代码。一旦我在电脑上,我会试一试。啊,是的,出于好奇,为什么“e”现在是function verifyOTP 的论点?是不是我们可以将“e”用于函数preventDefault()?再次感谢您的帮助。
  • 不客气,e 是参数名称,无论是e 还是event。如果解决了,请将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 2013-08-23
  • 2014-11-07
  • 2012-03-09
  • 2011-11-23
  • 1970-01-01
相关资源
最近更新 更多