我是新開發的web開發人員。通過AJAX調用PHP header()無法正常工作
現在我正在使用網站上的登錄功能。我使用Javascript/AJAX獲取用戶名和密碼,並將其發送到PHP文件以在MYSQL數據庫上進行驗證。這就是我要做的。
我的問題是爲什麼header()函數不能正常工作?我希望用戶登錄,她將被重定向到的個人資料頁(profile.php)
這裏的PHP(login.php中)的片段後:
$query = "SELECT * from user WHERE username = '$uname' AND password = md5('$pass');";
$ret = mysql_query($query) or die(mysql_error());
if(!$ret) {
$msg = "Invalid query " . mysql_error() . "\n";
$msg .= "Whole query " . $query;
die($msg);
}
$userid = -1;
while($row = mysql_fetch_array($ret)) {
$userid = $row["ID"];
}
$cnt = mysql_num_rows($ret);
if($cnt == 1) {
session_start();
$_SESSION["userid"] = $userid;
$_SESSION["uname"] = $uname;
echo "You have logged in successfully!";
header("Location: profile.php");
} else {
echo "Wrong Username/Password";
}
下面是對使用Javascript(AJAX的功能) :
var obj;
var url = "login.php";
var params = "uname=" + document.getElementsByName("uname")[0].value + "&pass=" + document.getElementsByName("pass")[0].value;
if(window.XMLHttpRequest) { // Major browsers
obj = new XMLHttpRequest();
obj.open("POST",url,true);
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.setRequestHeader("Content-length", params.length);
obj.setRequestHeader("Connection", "close");
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
if(obj.status == 200) {
// success
} else {
alert("Problem in returned data" + "Error status=" + obj.status);
}
}
}
obj.send(params);
XMLHttpRequest對象有一個'onload'屬性,所以你不必檢查狀態和readystate :) – user3105607 2014-02-08 22:42:29