执行PHP而不刷新页面

时间:2020-06-10 16:08:24

标签: javascript html jquery css ajax

单击提交按钮时,我想通过php执行javascript代码……此代码可以执行,但是页面会刷新.....我不希望页面刷新...我可以通过ajax或jquery实现它吗?

<html>
    <head>
        <style>
            .popup
            {
                visibility:hidden;
            }
        </style>
    </head>
    <body>
        <form method="post">
        <div id="Popup" class="popup">
            Sorry! The vehicle is already booked on the corresponding date.
            Select a different date or book another vehicle.
        </div>
        <input type="submit" name="submit" value="display">
        </form>
        <?php
            if(isset($_POST["submit"]))
            {
                echo '<script>document.getElementById("Popup").style.visibility="visible";</script>';
            }
        ?>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

您无法使用PHP执行此操作。如PaulProgrammer所述,PHP仅在生成页面时才可以执行,因为它是服务器端语言。您需要客户端语言(例如JavaScript)来执行此操作。这是您可以尝试的代码示例。不要仅以示例为例,而是要学习每个组件的作用:

<html>
    <head>
        <style>
            #popup
            {
                display:none;
            }
        </style>
    </head>
    <body>
        <button id="showbtn">Show Popup</button>
        <div id="popup">
            Sorry!The vehicle is already booked on the corresponding date.
            Select a different date or book another vehicle.
        </div>

        <script>
            const mypopup = document.getElementById("popup");
            const mybutton = document.getElementById("showbtn");

            mybutton.addEventListener('click', function(event) {
                mypopup.style.display = "block";
            })
        </script>

    </body>
</html>

答案 1 :(得分:-1)

尝试使用javascript在第二平面上执行代码