簡體   English   中英

如何防止頁面在表單提交后重新加載 - JQuery

[英]How to prevent page from reloading after form submit - JQuery

我正在為我的應用程序開發網站 class 工作,我遇到了最奇怪的問題。

我正在使用一些 JQuery 將表單數據發送到名為“process.php”的 php 頁面,然后將其上傳到我的數據庫。 奇怪的錯誤是頁面在提交表單后重新加載,我無法或我的生活弄清楚如何僅在后台打開 JQuery go。 這有點像首先使用 JQuery 哈哈。 無論如何,我會提交所有相關代碼,如果您需要其他任何東西,請告訴我。

<script type="text/JavaScript">

$(document).ready(function () {
  $('#button').click(function () {

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

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});
</script>
<div class= "main col-xs-9 well">
  <h2 style="color: black" class="featurette-heading">Join our mailing list!</h2>
  <form id="main" method = "post" class="form-inline">
    <label for="inlineFormInput">Name</label>
    <input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
    <label for="inlineFormInputGroup">Email</label>
    <div class="input-group mb-2 mr-sm-2 mb-sm-0">
      <input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe@email.com">
    </div>
    <!--Plan to write success message here -->
    <label id="success_message"style="color: darkred"></label>
    <button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button>
  </form>

如果相關的話,這是我的 php:

<?php
  include 'connection.php';

  $Name = $_POST['name'];
  $Email = $_POST['email'];

  //Send Scores from Player 1 to Database 
  $save1   = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')";

  $success = $mysqli->query($save1);

  if (!$success) {
    die("Couldn't enter data: ".$mysqli->error);

    echo "unsuccessfully";
  }

  echo "successfully";
?>

這是日志的截圖:

日志截圖

除非另有說明,否則<button>元素在放入表單時將自動提交表單。 您可以使用以下兩種策略:

  1. 使用<button type="button">覆蓋默認提交行為
  2. 在onSubmit事件中使用event.preventDefault()來阻止表單提交

解決方案1:

  • 優點:簡單更改標記
  • 缺點:顛覆默認表單行為,尤其是在禁用JS時。 如果用戶想點擊“輸入”提交怎么辦?

在按鈕標記中插入額外的type屬性:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

解決方案2:

  • 優點:即使禁用JS,表單也會起作用,並且尊重標准表單UI / UX,以便至少使用一個按鈕進行提交

單擊按鈕時阻止默認表單提交。 請注意,這不是理想的解決方案,因為您實際上應該聽取提交事件,而不是按鈕單擊事件

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

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

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

更好的變體:

在這個改進中,我們監聽從<form>元素發出的submit事件:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

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

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

更好的變體:使用.serialize()來序列化表單,但記住要在輸入中添加name屬性:

根據jQuery的文檔.serialize()需要name屬性才能工作:

要使表單元素的值包含在序列化字符串中,該元素必須具有name屬性。

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe@email.com">

然后在你的JS中:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

加載頁面時清除之前的 state....將此添加到 document.ready function。

if ( window.history.replaceState ) {
    window.history.replaceState( null, null, window.location.href );
}

暫無
暫無

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

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