簡體   English   中英

jQuery驗證AJAX表單

[英]jQuery validation AJAX form

我正在嘗試向我的ResetPassword函數添加驗證。 驗證它的工作正常,但是添加驗證后,我遇到了另一個問題,我的ResetPassword函數無法正常工作。有人可以朝正確的方向指導我嗎? 謝謝。

HTML代碼:

<div class="PopUpBG">
  <div class="PopUp">
    <h3 class="modal-title">
      <span>Reset PAssword</span>
    </h3>
    <form id="form">

      <input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>

      <input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>

    </form>
  </div>

</div>

ResetPassword和驗證代碼:

function ResetPassword(e) {

  var email = $("#ResetEmail").val();

  if ($("#form").validate()) {
    return true;
  } else {
    return false;
  }

  $(".PopUp").html("We have sent mail to you");

  $.ajax(
    {
      type: "POST",
      url: "/Account/loginRequestResetPassword",
      dataType: "json",
      data: {
        Email: email,
      },
      complete: function () {
        console.log("send");
        $(".PopUpBG").fadeOut();
      }
    })
}

問題是因為由於在if語句的兩種情況下都使用return語句,所以在發送AJAX請求之前總是退出該函數。

更改邏輯以僅在驗證失敗的情況下退出函數:

function ResetPassword(e) {
  if (!$("#form").validate())
    return false;

  $.ajax({
    type: "POST",
    url: "/Account/loginRequestResetPassword",
    dataType: "json",
    data: {
      Email: $("#ResetEmail").val().trim(),
    },
    success: function() {
      console.log("send");
      $(".PopUp").html("We have sent mail to you");
      setTimeout(function() {
        $(".PopUpBG").fadeOut();
      }, 10000); // fadeout the message after a few seconds
    },
    error: function() {
      console.log('something went wrong - debug it!');
    }
  })
}

還要注意,我修改了邏輯以僅在請求完成顯示成功的電子郵件。 您的當前代碼可以向用戶顯示“已發送電子郵件”消息,即使該功能仍然存在失敗的可能性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM