通过 Ajax 和 Js 重定向用户时,将显示文件的源代码,而不是图形界面

When redirecting the user via Ajax and Js, the source code of the file is displayed, instead of the graphical interface

提问人:Santiago Machado 提问时间:9/20/2023 最后编辑:ADysonSantiago Machado 更新时间:9/20/2023 访问量:41

问:

我目前正在从事一个学校项目,涉及使用 PHP(带有 PDO)、JavaScript 和 Ajax 实现登录系统。目标是根据用户类型将用户重定向到各自的仪表板。但是,我遇到了一个问题,即 Web 浏览器不显示预期的仪表板,而是显示源代码,包括底层结构。我附上了代码文件以供参考。

用户控制器 .php:

    <?php
    require_once("db.php");
    require_once('class.php');
    require_once('user-model.php');

    session_start();

    $response = array(); // Initialize the $response variable

    if (isset($_POST['user']) && isset($_POST['pass'])) {
       $mail = $_POST['user'];
       $contra = $_POST['pass'];

       $databaseCuatro = new Database();
       $conn = $databaseCuatro->getConnection();
       $sql = "SELECT email, contrasena, rol FROM usuarios WHERE email = 
       :mail";
       $stmt = $conn->prepare($sql);
       $stmt->bindParam(':mail', $mail);
       $stmt->execute();

        $usuario = $stmt->fetch();

        if ($usuario && password_verify($contra, $usuario['contrasena'])) 
    {
            // Valid credentials, create the session
            $_SESSION['loggedin'] = true;

        // Set the status based on the user's role
        if ($usuario['rol'] === 1) {
            $_SESSION['admin'] = $usuario;
            $response['status'] = 1;
        } elseif ($usuario['rol'] === 2) {
            $_SESSION['userdem'] = $usuario;
            $response['status'] = 2;
        } elseif ($usuario['rol'] === 3) {
            $_SESSION['useroferente'] = $usuario;
            $response['status'] = 3;
        }
    } else {
        $conn = $databaseCuatro->getConnection();

        if (!$databaseCuatro->checkMail($mail)) {
            $response['status'] = 5; // Email does not exist
        } else {
            $response['status'] = 4; // Incorrect username or password
          }
       }
    }

    // Now send the JSON response
    header('Content-Type: application/json;');

    echo json_encode($response);
    ?>

脚本表单.js:

    /* Ajax for login */
    function loginData(event) {
     event.preventDefault(); // Prevent the form from submitting 
     immediately

    var user = $('.input-user').val();
    var pass = $('.input-pass').val();

      let data = {
        user: user,
        pass: pass
      }

      /* Check login using Ajax */
      $.ajax({
      url: "user-controller.php",
      method: "post",
      data: data,
      dataType: "json",
      success: function (response) {
          if (response.status === 1) {
                  window.location.href = 'dashboard-admin.php';
              } else if (response.status === 2) {
                 window.location.href = 'dashboard-demandante.php';
              } else if (response.status === 3) {
                  window.location.href = 'dashboard-oferente.php';
              } else if (response.status === 4) {
                  showMessage("Incorrect username or password!");
              } else if (response.status === 5) {
                  showMessage("This account does not exist!");
              }
          },
            error: function (xhr, status, error) {
            console.log("Error in AJAX request: " + error);
          }
      });
    }

这是仪表板之一(它们都给了我同样的问题)

```<?php
include_once('db.php');
include_once('class.php');
include_once('user-controller.php');
include('header-admin.html');

if (isset($_SESSION['admin']) && $_SESSION['loggedin'] === true) {
    $admin = $_SESSION['admin'];
} else {
    header('Location: user-form.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();


$sql = "SELECT * FROM admin WHERE MailA = :mail";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':mail', $mail); 
$stmt->execute();
$adminData = $stmt->fetch(PDO::FETCH_ASSOC);

$conexion = null;
?>

<div class="container mt-4">
    <div class="row justify-content-center align-items-center">
        <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6">
            <div class="card text-center">
                <div class="card-header">
                    <h2> Bienvenido Administrador!</h2>
                </div>   
                <div class="card-body">
                    <div class="input-group justify-content-center  
align-items-center">
                    <form method="POST" action="dashboard-admin.php">
                        <button type="submit" class="btn btn-primary" 
name="btnPerfiles">Ver Perfiles</button>
                        <button type="submit" class="btn btn-danger" 
name="logoutAd">Logout</button>
                        </form>
                    </div>
               </div>
            </div>
        </div>
    </div>
</div>

<?php
if (isset($_POST['btnPerfiles'])) {
    header('Location: admin-perfiles.php');
}

if (isset($_POST['logoutAd'])) {
    header('Location: user-form.php');
    session_destroy();
}
?>```

javascript php mysql ajax pdo

评论

0赞 ADyson 9/20/2023
在99%的情况下,发生这种情况是因为您没有在支持PHP的环境中运行代码。请确保在开发计算机上使用适当的 Web 服务器,并通过http://localhost
1赞 ADyson 9/20/2023
附言....那么,它是否将您重定向到(例如)然后显示源代码而不是仪表板内容?或者您的意思是在此之前问题发生在其他页面上?目前还不完全清楚。instead of displaying the intended dashboarddashboard-admin.php
2赞 RiggsFolly 9/20/2023
似乎有点奇怪,如果user_controller可以工作,其他PHP代码应该可以工作
0赞 Santiago Machado 9/20/2023
嗨@ADyson,当我登录时,Js 将我发送到与用户类型相对应的仪表板,但我看到的不是网页(带有 css 的 html 结构),而是文件的源代码(仪表板)。
0赞 ADyson 9/20/2023
这真是太奇怪了......所以用户控制器 .php 上的登录脚本工作正常,但仪表板脚本却不能?因此,这似乎不太可能是与环境相关的问题,可能更可能是仪表板页面中的问题。您能否编辑您的问题并粘贴给您带来问题的仪表板 PHP 文件之一的代码,请

答: 暂无答案