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

时间:2010-08-05 23:38:52

标签: php

我有以下两个脚本文件(即formtest.html和calc.php)。 当我在calc.php上进行服务器端验证时,如何传递错误消息(即         $ err_msg回到formtest.html?

谢谢

<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!';
        }

        ?>

1 个答案:

答案 0 :(得分:1)

您需要使用Server Side Include将PHP输出引入HTML文件(如果需要保留为HTML文件),或者(更好的解决方案)将其全部包含在一个文件中像这样的文件:

(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>

不确定这是否有效,因为我把它写在了我的头顶。但这就是要点。希望有道理。 ;)

**更改了代码以反映您的评论。*

相关问题