如何在PHP代码中调用javascript函数?

时间:2013-02-20 10:09:06

标签: php javascript validation server-side-validation

在我的登录表单上,我正在进行服务器端验证,如果发生错误,我想在验证的控件下方显示这些错误。现在为此,我试图调用javascript函数在PHP代码中显示验证消息但无法调用。

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
    //here i want to call javascript function to display message    
}
}
?>
 <form action="login.php" method="POST">

 Username <input type="text" size="30" name="txtUsername" id="user" /><br />

 Password <input type="password" size="30" name="txtPassword" id="pass" /><br />

 <input type="submit" value="Login" name="loginSubmit"/>

</form>


<script type="text/javascript">

   function showMessage(value)
   {
    document.getElementById(value).innerHTML= value+"can not be empty."; 
   }
   </script>

请告诉我如何在表单中的验证控件下方显示服务器端验证。

4 个答案:

答案 0 :(得分:3)

像这样的东西

<html>
<head>
<script type="text/javascript">

   function showMessage(value)
   {
       document.getElementById(value).innerHTML= value+"can not be empty."; 
   }
   </script>
</head>
<body>
<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if($_POST['txtUsername']=='')
    {
        echo '<script> showMessage("txtUsername"); </script>';
    }
}
?>
 <form action="login.php" method="POST">

 Username <input type="text" size="30" name="txtUsername" id="txtUsername" /><br />

 Password <input type="password" size="30" name="txtPassword" id="txtPassword" /><br />

 <input type="submit" value="Login" name="loginSubmit"/>

</form>

</body>
</html>

答案 1 :(得分:3)

使用此

if($_POST['txtUsername']=='')
{
     echo '<script> showMessage("txtUsername"); </script>';
}

答案 2 :(得分:2)

你可以将你的php代码放在你喜欢的任何地方,让我们说在body like属性中。您可以尝试以下代码:

<body  <?php

        if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
  echo "onload = 'showMessage("VALUE")'";    
}
}
?> > // end of body start tag

 <form action="login.php" method="POST">

 Username <input type="text" size="30" name="txtUsername" id="user" /><br />

 Password <input type="password" size="30" name="txtPassword" id="pass" /><br />

 <input type="submit" value="Login" name="loginSubmit"/>

</form>
</body>

<script type="text/javascript">

   function showMessage(value)
   {
    document.getElementById(value).innerHTML= value+"can not be empty."; 
   }
   </script>

如果验证成功,php代码将不会回显任何内容,并且不会调用javascript函数。适合我:)。告诉我这是否有帮助。

答案 3 :(得分:1)

    <?php

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
      if($_POST['txtUsername']=='')
      {
      ?>
          <script>
             //Define the function somewhere in the top or in external js and include it.
            callyourfunction();
          </script>
      <?php
      }
    }
?>              //Its not working