执行 JavaScript 验证后文本消息消失



>我有一个表单,在将其发送到PHP之前,我正在做一些验证JavaScript,验证后的JavaScript函数会在页面底部的<p>标签中发布用户输入的文本;但是,此消息会短暂显示,然后消失...

如何使消息保留在页面中,并将其余数据发送到 PHP 脚本?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Us</title>
    <!-- Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!-- stylesheet for this form -->
    <link href="contact-stylesheet.css" rel="stylesheet">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript">
        function validateForm() {
            var message = "";
            var letters = /^[A-Za-z]+$/;        
            var name = document.forms["myForm"]["name"].value;
            var email = document.forms["myForm"]["email"].value;
            var subject = document.forms["myForm"]["subject"].value;
            var text = document.forms["myForm"]["text"].value;
            var outputMsg = "";
            if (name == null || name == "") {               
                message += "name field missing!n";
            }               
            if (name != "" && !name.match(letters)) {
                message += "Invalid name: only letters allowed!n";
            }
            if (subject == null || subject == "") {
                message += "Subject field is empty!n";
            }
            if (text == null || text == "") {
                message += "Text field is empty!n";
            }           
            if (message != "" ) {
                alert(message);
                return false;
            }
            outputMsg = "Message Sent!....n" + 
                        "Name: " + name + "n" +
                        "Email: " + email + "n" + 
                        "Subject: " + subject + "n" +
                        "Text: " + text + "n";
            document.getElementById("msg-result").innerHTML = outputMsg;
            return true;
        }    
    </script>
  </head>
  <body>
      <div class="row">
          <div class="hero-unit" style="padding:20px 100px">
            <h1>Contact Us</h1>
            <p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>       
        </div>
          <div class="col-sm-6">
            <div class="my-form">
                <form class="form-horizontal" name="myForm" action="" onsubmit="validateForm()" method="post">
          <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
            <div class="col-sm-8">
              <input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
            <div class="col-sm-8">
              <input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
            <div class="col-sm-8">
              <input type="text" name="subject" class="form-control" placeholder="Subject">
            </div>
          </div>
          <div class="form-group">
              <label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
              <div class="col-sm-8">
                <textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
              </div>    
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">Send</button>
            </div>
          </div>    
            </div> 
        </form>
          </div>
          <div class="col-sm-6">
              <div style="width:500px;heigth:350px;border:solid 1px brown">
                <h1>GOOGLE MAP HERE!</h1>
              </div>
             <!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL">                     -->
          </div>      
      </div>
      <div class="col-sm-6" style="padding:10px 140px">
              <p id="msg-result"></p>
            <!-- display form result message here! -->
      </div>
    <!--
    Welcome <?php echo $_POST["name"]; ?><br>
    Your email address is: <?php echo $_POST["email"]; ?>
    -->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

这是因为您正在更新字段中的文本,然后提交给php(自页面刷新以来擦除所有字段)。您可以设置隐藏元素来保存要显示的值,以便它们发布到 php,然后您可以将它们回显到您想要的位置。另一种方法是对 php 进行 ajax 调用以进行更新,而不是回发到同一页面。

所以使用 ajax,你会做这样的事情:

formSubmit()
{
  //do validation
  //do a jquery post to a php page
  $.ajax
  ({
    type: "POST",
    //the url of the php page
    url: 'test.php',
    dataType: 'json',
    async: false,
    //json object to sent to the authentication url
    data: '{"test": "info"}',
    success: function (result) {
    //update stuff
    }
  })
  return false;
}

我认为表格是在检查后提交的。您必须返回结果(如果 validateForm() 为 false,则取消提交):

onsubmit="return validateForm();"

或防止默认值:

onsubmit="return validateForm(event);"

function validateForm(event) {
    ...
    event.preventDefault();

最新更新