简体   繁体   English

如何将服务器端验证消息传递回客户端?

[英]How to pass the server side validation messages back to client?

I have the following two script files (ie, formtest.html and calc.php). 我有以下两个脚本文件(即formtest.html和calc.php)。 When I do the server side validation on calc.php, how do I pass the error message (ie $err_msg back to the formtest.html? 当我在calc.php上进行服务器端验证时,如何传递错误消息(即$ err_msg回到formtest.html?

Thank you 谢谢

<html>
    <head>
        <title>Form Test</title>
    </head>
    <body>

    <form method="post" action="calc.php">
    <pre>
          Loan Amount <input type="text" name="principle" />
                      <input type="submit" />
    </pre>
    </form>
    </body>
    </html>

.

// calc.php

        $err_msg = ''; 

        if ( !empty(isset($_POST['principle'])) )
        {
            // process the form and save to DB
        } else {
         $err_msg .= 'Loan Amount is empty!';
        }

        ?>

You will either need to use a Server Side Include to bring in the PHP output into the HTML file (if it needs to remain an HTML file), or (a better solution) would be to include it all in one file like so: 您可能需要使用服务器端包含将PHP输出导入HTML文件(如果需要保留HTML文件),或者(一种更好的解决方案)是将所有内容都包含在一个文件中,如下所示:

(calc.php) (calc.php)

<?php
    $err_msg = '';
    if (isset($_POST['principle']) && !empty($_POST['principle']) )
    {
        // process the form and save to DB
    } else {
     $err_msg .= 'Loan Amount is empty!';
    }
?>
<html>
<head>
    <title>Form Test</title>
    <script type="text/javascript">
    <!--
         var errMsg = '<?php echo $err_msg; ?>';
         // Do something with javascript here.
    -->
    </script>
</head>
<body>
<div class="error">
<?php 
    // Or echo it inline with your HTML. 
    echo $err_msg;
?> 
</div>
<form method="post" action="calc.php">
<pre>
      Loan Amount <input type="text" name="principle" />
                  <input type="submit" />
</pre>
</form>
</body>
</html>

Not sure if that's valid as I wrote it off the top of my head. 当我从头顶上写下它时,不确定那是否有效。 But that's the gist. 但这就是要旨。 Hope that made sense. 希望有道理。 ;) ;)

**Changed code to reflect your comment.* **更改代码以反映您的评论。*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM