0

我正在做的 php 是文本框一个空值它将打开一个警报框(我在这里使用 javascript)

这是我的代码

    <?php 
    include('config.php');

        if(isset($_POST['submit'])){
        $username=$_POST['username'];

    ?>

    <script>
        function validate(){
        if(document.forms[0].username.value==""){
          window.alert("You must enter both values");
          return false;
        }
        }
    </script>

    <?php
    }
    ?>



<html>
<div><p>Member Profile</p>
    <form action="testing.php" method="POST" onsubmit="return validate();">
    Username<br>
    <input class="user" type="text" name="username" id="username" /><br>


<input type="submit" name="submit" value="register" />
</form>
</div>

</html>

问题是我必须在警报显示之前单击 2 次

请帮我解决这个问题

4

1 回答 1

3

这是因为脚本在 phpif(isset){}块内,单击提交表单,生成脚本,然后第二次运行.. 试试这个设置:

<?php
    include ('config.php');

    if (isset($_POST['submit']))
    {
        $username = $_POST['username'];
    }
?>
<html>
    <head>
        <script>
            function validate () {
                if (document.forms[0].username.value == "") {
                    window.alert("You must enter both values");
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <div>
            <p>
                Member Profile
            </p>
            <form action="testing.php" method="POST" onsubmit="return validate();">
                Username
                <br>
                <input class="user" type="text" name="username" id="username" />
                <br>

                <input type="submit" name="submit" value="register" />
            </form>
        </div>
    </body>
</html>

编辑:

我已经将脚本标签移到了 head 标签内。我不确定将脚本放在外面是否有任何影响,但只是为了确保我已经移动了它。

第二次编辑:(强迫症开始了)

我添加了正文标签,不确定您是否复制并粘贴了此代码,但对我来说看起来很奇怪 :)

于 2012-11-30T09:43:16.500 回答