首页 > 解决方案 > 执行php而不刷新页面

问题描述

我想在单击提交按钮时通过 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>

标签: javascripthtmljquerycssajax

解决方案


你不能用 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>

推荐阅读