【问题标题】:how to display an alert after redirect to another page重定向到另一个页面后如何显示警报
【发布时间】:2018-07-20 00:35:59
【问题描述】:

登录表单 (index.php) 已经创建。当表单提交时,用户名和密码被传递到另一个页面(login-controller.php)。验证后,如果用户名或密码不正确,用户在 login-controller.php 中显示警报框后被重定向到登录表单(index.php)。但我想在重定向到登录后显示一个警报框,如“无效的登录凭据”形式(index.php)。我该如何解决这个问题。 login-controller.php 的代码如下。

<?php

session_start();
if (isset($_SESSION['username'])) {
    header('Location: ../service/index.php');
}

include '../include/conn.php'; //database connection

if (isset($_POST["submit"])) {
    if (empty($_POST["username"] && $_POST["password"])) {
        header('Location: index.php');
    } else {
        $username = mysqli_real_escape_string($conn, $_POST["username"]);
        $password = mysqli_real_escape_string($conn, $_POST["password"]);
        $password = md5($password);
        $sqli = "SELECT * FROM user WHERE name = '$username' AND password = '$password'";
        $result = $conn->query($sqli);
        $count = mysqli_num_rows($result);
        if ($count == 1) {
            $_SESSION['username'] = $username;
            header('Location: ../service/index.php');
        } else {
            include '../include/bootstrap.php'; //bootstrap js and css
            echo '<div class="alert alert-danger"><strong>Oops!</strong> Invalid Login Credentials.</div>';
            echo "<script>setTimeout(\"location.href = 'index.php';\",3000);</script>";
        }
    }
}
?>

【问题讨论】:

  • 在重定向url中添加一些GET参数,在登录页面检测并显示通知
  • 在 PHP 中编写 javascript 代码而不是使用一些查询字符串重定向到登录页面并在登录页面上编写代码以检查该查询字符串是否错误然后显示弹出窗口是一种不好的做法。
  • 您可以使用会话或本地存储

标签: javascript php


【解决方案1】:

使用会话变量可以显示警报:

$_SESSION['alerts'][] = "Test Alert";
$_SESSION['alerts'][] = "Another Test Alert";

然后在您的配置中,或在您拥有的每个页面上执行的任何其他 .php 文件中(如果您有模板系统,请在模板中执行此操作)执行以下操作:

if(isset($_SESSION['alerts'])){
    foreach($_SESSION['alerts'] as $alertmessage){
        echo '<div class="alert">' . $alertmessage . '</div>';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多