javascript - 提交表单后会发生什么?

标签 javascript html

这可能是一个宽泛的答案,但我会尝试缩短它。我想做的是使用表单从用户那里获取一些信息并使用 JavaScript“验证表单”。如果验证成功,则提交表单。一旦发生这种情况,我将尝试检索使用 java 脚本输入表单的数据并显示在同一页面上。(使用模式)

虽然我认为我的逻辑是错误的。一旦表单验证,它就会被提交?一旦提交页面刷新?因此输入数据丢失?这可能是我不断在模态中获取空值的原因吗?

这是表单的 html

<div class="feedback-background">
<div class="feedback-content">
    <div class="close">+</div>
    <img src="../Images/Images2/feedbackimg1.jpg" alt="Givefeedback" style="width:100px;height:100px;">

    <form name="FeedbackForm" action="/action_page.php" onsubmit="return validateForm();displayContent();"
          method="get">
        Name:
        <input id="Name" name="Name" type="text" placeholder="Name">
        E-Mail:
        <input id="E-mail" name="E-mail" type="email" placeholder="E-mail">
        What do you think about us?<br>
        <textarea id="comment" rows="6" cols="33" name="comment"></textarea>
        <br>
        How would you rate us ?
        <br>

        <label><input type="radio" name="rating" id="rating1" value="Excellent" checked>Excellent</label>
        <label><input type="radio" name="rating" id="rating2" value="Very Good">Very Good</label>
        <label><input type="radio" name="rating" id="rating3" value="Average">Average</label>
        <label><input type="radio" name="rating" id="rating4" value="Poor">Poor</label>
        <label><input type="radio" name="rating" id="rating5" value="Extreamly Poor">Extremely Poor</label>
        <input type="submit" id="submit" value="Submit">
    </form>
</div>

这是模式的 HTML,其中输入数据将再次向客户显示

<div class="popup">
    <div class="popuptext" id="myPopup"><p>Thank you <span id="username"></span> ,<br>Your feedback has been
        recorded.<br>
        <br>You commented that"<span id="usercomment"></span>" <br><br>and rated our website "<span
                id="userrating"></span>".
        <br><br>Thank you
        for taking your time to do so.<br><br>You will now be re-directed automatically</p>
    </div>
</div>

这是我用于表单的 CSS

/*----------comment form----------*/

.feedback-background{
 width: 100%;
 height: 100%;
 background-color: rgba(0,0,0,0.7);
 position: absolute;
 top: 0px;
 display: flex;
 align-items: center;
 justify-content: center;
 display:none;
 }
 .feedback-content{
  width: 500px;
  height: 550px;
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  position:relative;


  }
 #submit{text-transform:uppercase;
 padding:6px 2px;
 margin-right: 40px;
 margin-top: 20px;

 background: #ee0c6e;
 font-weight:600;
 color:white;
 border-radius: 3px; 
 font-size: 10px;
 min-width: 100px;
 text-decoration:none
 }

 input {
 width: 50%;
 display: block;
 margin: 10px 0px;

   }

   label {
   display: block;
  }

 input[type="radio"]{
 width: auto;
 display: inline;
  }
 input[type="submit"]{
 width:10em;height: 2em;
 cursor:pointer;

 }
.close{
position:absolute;
top:0px;
right:14px;
transform:rotate(45deg);
font-size:42px;
cursor:pointer;
 }
#feedbacksubmit{
margin-left:600px;
margin-bottom:50px;
background-color:#484848;
border-radius:14px;
padding:10px;
cursor:pointer;
color:white;
outline:none;
}

这是我用于弹出模式的 CSS

/*-----popup----*/
.popup{
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
position: absolute;
top: 0px;
display: flex;
align-items: center;
justify-content: center;
display:none;

 }
.popuptext{
  width: 100px;
 height: 350px;
 background-color: #000025;
 border-radius: 4px;
 padding: 20px;
 position:relative;
 color:#fff;
 width: 20%;
 height:30%;
 display: block;
 margin: 10px 0px;
 text-align:center;
 margin-left:0px;
 margin-bottom:80px;
 }

 #logo{

margin-right:100px;
float:left;
}

这是我使用过的JavaScript。

/*------comments form-----*/

document.getElementById('feedbacksubmit').addEventListener('click',
    function () {
        document.querySelector('.feedback-background').style.display = 'flex';
    }
)


document.querySelector('.close').addEventListener('click',
    function () {
        document.querySelector('.feedback-background').style.display = 'none';
    }
)


function displayContent() {
    var name = document.getElementById("Name").value;
    var comment = document.getElementById("comment").value;

    var ratings = document.getElementById('rating');
    var rate_value;
    for (var i = 0; i < rating.length; i++) {
        if (rating[i].checked) {
            rate_value = rating[i].value;
        }
    }

    /*these lines are used to write the details into the new modal*/
    document.getElementById("username").textContent = name;
    document.getElementById("usercomment").textContent = comment;
    document.getElementById("userrating").innerHTML = rate_value;

    return "";
}


function closePopup() {

    document.querySelector('.popup').style.display = 'none';
}

/*-------validation-----*/
function validateForm() {
    var x = document.forms["FeedbackForm"]["Name"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
    var z = document.forms["FeedbackForm"]["E-mail"].value;
    if (z == "") {
        alert("Please enter your E-mail address to proceed");
        return false;
    }
    var y = document.forms["FeedbackForm"]["comment"].value;
    if (y == "") {
        alert("Comment section can not be empty");
        return false;
    }

    var a = 0, rdbtn = document.getElementsByName("rating")
    for (i = 0; i < rdbtn.length; i++) {
        if (rdbtn.item(i).checked == false) {
            a++;
        }
    }
    if (a == rdbtn.length) {
        alert("Please select a rating according to you");
        return false;
    }


    document.getElementById('submit').addEventListener('click',
        function () {
            document.querySelector('.feedback-background').style.display = 'none';
            document.querySelector('.popup').style.display = 'flex';
        }
    )
}

有更好的方法吗?我该怎么做呢?我做错了什么

最佳答案

无需太仔细地查看您的代码,这里是所要求的“大局”概述,介绍了提交表单时发生的情况以及如何验证表单。

首先,表单以及提交后会发生什么。

当您单击提交按钮时,您的表单数据将被发送到表单标记上指定的文件 - 在您的情况下为“/action_page.php”。到达的是许多变量(又名“键值对” - 但它们是具有名称和值的变量)。请注意,“变量名称”是 name= 中指定的内容。 (例如)输入字段的属性,“变量内容”是输入到(例如)输入字段中的任何内容。

您的后端 PHP 文件需要使用 $_POST 或 $_GET 命令为每个项目创建适当的 PHP $variables,具体取决于您在表单标记的“method=”属性中使用的方法。例如,您的表单有一个名为 name=comment 的文本区域元素。 。在PHP端,你可以这样写:

$cmt = $_GET['comment'];

然后很快!您在 PHP 变量 $cmt 中拥有用户的评论。

您可以在此阶段进行验证,或者您可以在提交文件之前验证 javascript 中的代码(请注意,javascript 可以拦截表单提交过程并停止它,或继续它。

然后,您的 PHP 文件可以将用户发送回同一页面(在这种情况下,您需要顶部的 <? php> 部分来处理该问题),或者完全发送到另一个页面。

重要说明:

  1. 重要提示:来自您指定的action= PHP 文件的位置,您可能会遇到一些麻烦,因为您以斜线开头。这会将操作系统发送回文件系统的根目录以查找您的文件,但这可能不是您想要的。现在,输入 "action_page.php"文件与您的 index.php 位于同一位置文件并删除前导斜杠。

  2. 一开始,不要使用同一个 PHP 文件来接收用于向用户显示表单的表单。 AJAX 也是如此(实现这一点)。首先做一些事情,这样你就很容易理解这个过程,然后让它变得更酷。

  3. 您可以在提交前使用 JS 验证用户数据,也可以在提交后使用 PHP 验证用户数据。但是,可以在 DevTools (F12) 控制台中读取、调试甚至更改 javascript - 因此,除了像“字段留空吗”这样的 super 基本内容之外,不要在 javascript 中进行重要验证。

  4. 永远不要相信用户数据。有些用户是黑客,如果您不清理他们输入的数据,他们就可以拥有您。研究sanitizing user datathis also将帮助您开始理解部分。

AJAX

当您提交表单时,屏幕将刷新。那么那些填写表格、提交后没有任何刷新但更改会在现有页面上更新的网站呢?这是通过 AJAX 完成的。

AJAX 确实非常简单——几乎比表单还要简单。开始使用 AJAX 的基本规则与我上面的注释相同:拥有与用户当前所在的不同的后端 PHP 文件。

坦率地说,现在我们已经不太使用表单了。几乎我们过去用表单做的所有事情现在都用 AJAX 来做——而且很简单!

那么 AJAX 是如何工作的呢?本质上,javascript 将表单数据(参见下面的示例!)发送到指定的 PHP 文件,该文件处理数据和 echo回来了回应。您收到该响应,将其分解为变量,并相应地更改页面。有关更多信息,请参阅下面的引用资料。

注意:如果您花十分钟尝试下面引用帖子中的示例,您将节省几个小时的时间。只需在您自己的服务器上重现这些示例并使用它们即可。

引用文献:

How a form works

HTML Forms vs Ajax

Simple overview of AJAX

Simple login system with ajax

关于javascript - 提交表单后会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943588/

相关文章:

javascript - Nodejs中如何区分文本文件和json文件

php - 如何通过强制另存为选项来保存网页的内容/文本

javascript - 使用 Javascript 检测 Windows 8 屏幕键盘

javascript - 根据托管的 URL 加载特定的 JS 文件

javascript - 如何读取 json 配置文件并将该参数设置为 ajax

jquery - 根据特定响应区域定位div

Python:引用表格中的行

html - 绝对位置不起作用( Bootstrap )

javascript - jquery 滚动效果不适用于 iphone

javascript - 无法访问页面内容