Javascript 表单提交后如何防止页面重新加载 - JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45634088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:07:58  来源:igfitidea点击:

How to prevent page from reloading after form submit - JQuery

javascriptphpjqueryhtmlforms

提问by Casey.PhillipsTMC

I am working on a website for my app development class and I have the weirdest issue.

我正在为我的应用程序开发课程开发一个网站,但我遇到了最奇怪的问题。

I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else.

我正在使用一些 JQuery 将表单数据发送到名为“process.php”的 php 页面,然后将其上传到我的数据库。奇怪的错误是页面在提交表单时重新加载,我无法或我的生活弄清楚如何让 JQuery 在后台继续运行。这就是首先使用 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="[email protected]">
    </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>

This is my php if its relevant:

如果相关,这是我的 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";
?>

This is a screenshot of the log:

这是日志的截图:

screenshot of log

日志截图

回答by Terry

The <button>element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

<button>除非另有说明,否则该元素在放置在表单中时将自动提交表单。您可以使用以下两种策略:

  1. Use <button type="button">to override default submission behavior
  2. Use event.preventDefault()in the onSubmit event to prevent form submission
  1. 使用<button type="button">覆盖默认提交行为
  2. 使用event.preventDefault()在onSubmit事件,防止表单提交

Solution 1:

解决方案1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?
  • 优点:对标记的简单更改
  • 缺点:颠覆了默认的表单行为,尤其是在禁用 JS 时。如果用户想点击“回车”提交怎么办?

Insert extra typeattribute to your button markup:

type按钮标记中插入额外的属性:

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

Solution 2:

解决方案2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission
  • 优点:即使禁用了 JS,表单也能工作,并尊重标准表单 UI/UX,至少使用一个按钮进行提交

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

单击按钮时防止默认表单提交。请注意,这不是理想的解决方案,因为您实际上应该监听提交事件,而不是按钮单击事件

$(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");
      });
  });
});

Better variant:

更好的变体:

In this improvement, we listen to the submit event emitted from the <form>element:

在这个改进中,我们监听从<form>元素发出的提交事件:

$(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");
      });
  });
});

Even better variant: use .serialize()to serialize your form, but remember to add nameattributes to your input:

更好的变体:用于.serialize()序列化您的表单,但请记住name为您的输入添加属性:

The nameattribute is required for .serialize()to work, as per jQuery's documentation:

根据jQuery 的文档,该name属性是.serialize()工作所必需

For a form element's value to be included in the serialized string, the element must have a name attribute.

对于要包含在序列化字符串中的表单元素的值,该元素必须具有 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="[email protected]">

And then in your JS:

然后在你的 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");
    });
  });
});