发送表单和重新加载页面后如何显示警报?

时间:2018-07-14 07:08:04

标签: php

正如标题所述,发送表单并重新加载页面后如何显示警报?

我的代码如下:

<?php
    if (isset($_POST['add_user'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        if (!empty($username) && !empty($password)) {
            //SQL - Adding user to database
            //And i should reload page, to prevent resending form later
            //But i also want an alert after page reload
        } 
    }
?>

2 个答案:

答案 0 :(得分:0)

您可以这样做:

//functions.php
<?php
    $current_page = basename($_SERVER['PHP_SELF']);

    function AntiFormResend($alert, $location) {
        $_SESSION["status"] = $alert;
        header("Location: $location");
        exit(0);
    }
?>

//index.php
<?php
    require 'functions.php';
    if (isset($_POST['add_user'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        if (!empty($username) && !empty($password)) {
            //SQL - Adding user to database
            $alert = '<div class="alert">Success: User added</div>';
            AntiFormResend($alert, $current_page);
        } else {
            $alert = '<div class="alert">Error: User not added</div>';
            AntiFormResend($alert, $current_page);
        }
    }
?>
<html>
    <head></head>
    <body>
        <?php
          if (isset($_SESSION["status"])) {
            echo $_SESSION['status'];
            unset($_SESSION["status"]);
          }
        ?>
    </body>
</html>

答案 1 :(得分:0)

最简单的解决方案是重定向回您的原始表单,并在URL中添加一个参数,例如:header("Location: /myForm.php?success=true")

然后就这么简单(在myForm.php中):

<?php
if (isset($_GET['success']) && $_GET['success'] === 'true') {
  echo "<script>alert('Success!');</script>";
}