Can't use header

I'm trying to make my PHP file redirect to an HTML file.

My website is constructed this way:

HTML ==> js seperate file (using angular) ===> PHP file

Then the php calls header function- but instead of redirecting, it prints the code of the HTML page I'm trying to open.

I haven't echoed anything before the calling the header function (though I've used one header in the beginning of the PHP file for Access Control).

I've also tried echo the "meta http equiv" tag with the wanted URL, but it just printed the tag.

Maybe it's because I'm using seperate files for php, js and HTML ?

Thanks!

Here's my PHP code:

header("Access-Control-Allow-Origin: *");
//header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = '';

// Create connection
$conn = mysqli_connect($servername, $username, $password, "myDB");
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$client_data = file_get_contents("php://input");
$json = json_decode($client_data);
$sql = "SELECT Password FROM users WHERE Name="". $json->username .""";
$result = $conn->query($sql);
if ($result->num_rows >0) {
    while ($row = $result->fetch_assoc()) {
        if (password_verify($json->password ,$row["Password"])) {
            header ('location: http://localhost/KickStartProject/views/register.html');
        } else {
            echo "Password didn't match.....";
        }
    }
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

mysqli_close($conn);

As @chris85 pointed out in his comment, ajax requests doesn't affect current document's location. You should make redirection like this:

<?php
header("Access-Control-Allow-Origin: *");
...
if (!$conn) {
    die(json_encode(["status"=>"err", "msg" => "Connection failed: " . mysqli_connect_error()]));
}
...
    if(password_verify ($json->password ,$row["Password"]) ){

        die(json_encode(["status"=>"ok", "redirect" => "/KickStartProject/views/register.html"]));
    }else{
        die(json_encode(["status"=>"err", "msg" => "Password didn't match....."]));
    }
...

And in yours javascript:

...
$.getJSON('/url-to-php', {...})
 .success(function(response) {
     if (response.status != "ok")
         alert(response.msg);
     else
         document.location.href = response.redirect;
 });
...
链接地址: http://www.djcxy.com/p/12414.html

上一篇: 在PHP中使用锚点标记重定向到另一个页面

下一篇: 无法使用标题