在javascript中重定向无效

时间:2018-05-28 00:17:05

标签: javascript php html

<?php
session_start();
include ("dbconnectie.php");
if(isset($_SESSION['on'])) {
header("location:homepage.php"); }
if(isset($_POST['login'])) {
      $username = $_POST['username'];
      $password = sha1($_POST['password']);
      $query = $db->prepare("SELECT * FROM account
                            WHERE username = :user
                            AND password = :pass"); 
      $query->bindParam("user", $username);
      $query->bindParam("pass", $password);
      $query->execute();
      $result = $query->fetch(PDO::FETCH_ASSOC);
      $id1 = $result['id_u'];
      if($query->rowCount() == 1) {
      $_SESSION['on'] = $username;
      $_SESSION['id_u'] = $id1;
      //header('location: homepage.php');
      } else {
        echo "The username and password do not match";
      }
        echo "<br>";
    }
?>
<html>
    <head>
    <title>L O G I N</title>
    <link rel="shortcut icon" href="images/jfk.ico" type="image/x-icon">
    <link rel="stylesheet" type="text/css" href="css/signin.css">
    <link rel="stylesheet" type="text/css" href="css/snackbar.css">
    </head>
    <header>
         <?php
            include("#nav.php");

        ?>
    </header>
<form class="modal-content" method="post" action="">
    <div class="container">
    <h1>I N L O G G E N</h1>
    <hr>

    <label>G E B R U I K E R S N A A M</label>
    <input type="text" name="username" placeholder="Gebruikersnaam Invullen"><br>

    <label>P A S S W O R D</label>
    <input type="password" name="password" placeholder="Password Invullen"><br>

    <button type="submit" class="submit" name="login" value"login" onclick="myFunction()">INLOGGEN</button>
    <div id="snackbar">U bent Ingelogd.</div>
    </div>
    <script>
    function myFunction() {
    // Get the snackbar DIV
    var x = document.getElementById("snackbar");

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
    window.location.href = "homepage.php";
    }
    //window.location.assign("homepage.php");
    </script>

</form> 
</html>

在HTML脚本内部的底部,我有window.location.assign尝试在登录并显示小吃栏后重定向,但是它只是在顶部添加了一个白色条而不是重定向。我想要它做的是点击登录后,它运行该脚本。这会稍微弹出3秒然后重定向到主页。

1 个答案:

答案 0 :(得分:0)

您可以执行event.preventDefault(),以便停用提交按钮的默认提交操作,并运行所有必需的代码。

function myFunction() {
  // Get the snackbar DIV
  var x = document.getElementById("snackbar");

  // Add the "show" class to DIV
  x.className = "show";

  // After 3 seconds, remove the show class from DIV

  setTimeout(function() {
    x.className = x.className.replace("show", "");
    window.location.href = "homepage.php";
  }, 3000);

}
document.querySelector('button[name="login"]').addEventListener("click", function(event) {
  event.preventDefault()
  myFunction();
});