如果使用表单,则重定向有效,但如果从javascript调用则无效

时间:2012-07-10 12:11:32

标签: jquery redirect

PHP代码是:

<?php

// Inialize session
session_start();

// Include database connection settings
include('config.inc');

// Retrieve username and password from database according to user's input
$sql ="SELECT * FROM user WHERE (email = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['password'])) . "')";

$login = mysql_query($sql);


// Check username and password match
if (mysql_num_rows($login) == 1) {
    // Set username session variable
    $_SESSION['username'] = $_POST['username'];
    // Jump to secured page
    header('Location: http://localhost/site/client/index.php');
}
else {
    // Jump to login page
    header('Location: http://localhost/site/acces-client/index.php');
}

?>

这有效:

以下表单可以成功地让用户登录并重定向:

<table border="0">
<form method="POST" action="loginproc.php">
<tr><td>Email:</td><td>:</td><td><input type="text" name="username" size="30"></td></tr>
<tr><td>Mot de passe:</td><td>:</td><td><input type="password" name="password" size="30"></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="submit" value="Envoyer"></td></tr>
</form>
</table>

这不起作用 通过“不起作用”,我的意思是没有重定向。虽然调用了正确的URL(http://localhost/site/client/index.php)。

$.post("http://localhost/site/loginproc.php", {username: email, password: motdepasse})
    .success(function(result3){
    });

2 个答案:

答案 0 :(得分:1)

要使重定向生效,您需要以下内容:

$.post("http://localhost/site/loginproc.php", {username: email, password: motdepasse})
    .success(function(result3){
        // won't reach here, since the php script never returns a 200 OK
    })
    .error(function(jqXHR, textStatus, errorThrown) {
        if(jqXHR.status == 302 || jqXHR.status == 301) {
            // 301 or 302 means redirected (perm, temp respectively)
            window.location.href = jqXHR.getResponseHeader('Location');
        }
    });

答案 1 :(得分:0)

以下作品:

$.post("http://localhost/site/acces-client/loginproc.php", {username: email, password: motdepasse})
        .success(function(jqXHR, textStatus, errorThrown) {
        window.location = 'http://localhost/site/client/index.php';
    })
});