我现在一直在开发一个网站,我已经坚持了很长一段时间。看,我的索引有一个普通的PHP页面,在该页面上有一个注册用户登录的按钮。我有一个JavaScript函数,通过AJAX处理请求,然后将其发送到PHP页面, login.php中。我发现该函数有效,它将我登录,分配我的会话变量,如后面的PHP页面所示,但不显示我已设置的通知。我还要提一下xmlhttp.responseText
的选项是注册期间唯一可用的选项。管理员当然除外,它将在数据库本身中被更改。最后一件事,如果我输入了错误的详细信息,xmlhttp.responseText = 'Wrong'
然后按预期显示通知。
JavaScript函数代码:
function login(name, pass) {
var xmlhttp;
var check = 0;
if(name == "") {
alert("Please enter your username");
check = 1;
}
if(pass == "") {
alert("Please enter your password");
check = 1;
}
if(check != 0) {
return;
}
if(window.XMLHttpRequest) { // Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // Code for IE5, IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var resp = xmlhttp.responseText;
if(resp == "Wrong") {
alert("The details you have entered are incorrect");
return;
}
if(resp == "user") {
alert("Welcome back!");
return;
}
if(resp == "developer") {
alert("Welcome back, developer!");
return;
}
if(resp == "admin") {
alert("Welcome back, Admin!");
return
}
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 404) {
alert("The login page was not found, please try again later");
}
}
xmlhttp.open("GET", "login.php?name="+name+"&pass="+pass, true);
xmlhttp.send();
}
这是PHP页面,login.php:
<?php
include "base.php";
$username=mysql_real_escape_string($_GET['name']);
$password=md5(mysql_real_escape_string($_GET['pass']));
$checkLogin=mysql_query("SELECT * FROM Users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checkLogin) == 1) {
$login=mysql_fetch_array($checkLogin);
$_SESSION['ID'] = $login['ID'];
$_SESSION['Username'] = $username;
$_SESSION['Email'] = $login['Email'];
$_SESSION['First'] = $login['Fist'];
$_SESSION['Last'] = $login['Last'];
$_SESSION['Type'] = $login['Type'];
echo $_SESSION['Type'];
} else {
echo "Wrong";
}
?>