如何使用Ajax标头

时间:2017-05-04 22:16:09

标签: javascript php jquery ajax

我正在使用jQuery和Ajax创建登录检查器,我正在调用query.php来验证用户名和密码。如果它们不匹配,将显示警报,如果它们是正确的,它将把用户重定向到另一页。 错误消息正常工作。 问题是,当我输入正确的用户名和密码时,页面不会重定向。 在我的情况下,我被重定向两次,从login.php到query.php再到groupes.php或seance.php

query.php

<?php
require('queries/dbsetup.php');

$username = $_POST['username'];
$password = $_POST['password'];
$type = "";
if (empty($username) || empty($password)) { ?>
    <script>
        sweetAlert("Oops...", "Veuillez remplir tous les champs !", "error");
    </script>
<?php
} else {
echo $type;
switch ($_POST['type']) {
case 'etudiant' : $type = 'etudiant';break;
case 'enseignant' :$type = 'enseignant';break;
}

// Check the username and password
$query = "SELECT username FROM ".$type." where username = '".$username."' AND password ='".$password."' ;";
$set = mysqli_query($conn,$query);
$run = mysqli_fetch_array($set);
$id = $run['username'];

// Save the type
$_SESSION['type'] = $type;


if (!empty($id)) {
$_SESSION['user_id'] = $username;

switch ($type) {
case 'etudiant':
header('location: ../groupes.php',true);exit;break;
    case 'enseignant':
header('location: ../seance.php',true);exit;break;

}

} else { ?>
    <script>
        sweetAlert("Oops...", "Le nom d'utilisateur et le mot de passe ne sont pas identique !", "error");
    </script>
    <?php
}
}

?>

的login.php

<form action="query.php" method="post" id="e1" class="">
              <h4>Nouvelle seance</h4>
              <input name="username" placeholder="Username" type="text" class="form-control">
              <input name="password" placeholder="Password" type="password" class="form-control">
              <input name="type" placeholder="Type" type="text" class="form-control"> 
              <button id="login">Login</button>                 
              <p id="result"></p>
</form>

login.js

$('#e1').submit(function(){
 return false;
});

$('#login').click(function(){
 $.post(
 $('#e1').attr('action'),
 $('#e1 :input').serializeArray(),
 function(result){
 $('#result').html(result);
 }
 );
});

1 个答案:

答案 0 :(得分:0)

您可以通过告诉客户端通过javascript加载新页面来实现所需的行为。

您可以更改这些行

switch ($type) {
    case 'etudiant':
        header('location: ../groupes.php',true);exit;break;
    case 'enseignant':
        header('location: ../seance.php',true);exit;break;
}

switch ($type) {
    case 'etudiant':
        ?>
        <script>
            window.location = "../groupes.php";
        </script>
        <?php
        exit;
        break;
    case 'enseignant':
        ?>
        <script>
            window.location = "../seance.php";
        </script>
        <?php
        exit;
        break;
}