我的问题出在我的登录页面上,我知道这不是用于测试目的。我的错误是,一旦我输入我的详细信息,它应该将它们发送到服务器以验证它们与数据库,然后将我重定向到下一页。
我知道服务器端代码正常工作,因为我已经使用Postman测试了它,它返回true。我认为我的问题是当我调用$ srvmsg时,这是因为每次我点击提交它都会向我发送错误消息“错误用户名和密码不正确”。
我的代码:
<div class="container">
<fieldset>
<legend>Login</legend>
<h2 class="form-signin-heading">Please sign in</h2>
<br>
<label for='username' class="sr-only">Username:</label>
<input class="form-control" type='text' name='username' id='username' maxlength="50" placeholder="Username" />
<br>
<label for='password' class="sr-only" >Password*:</label>
<input class="form-control" type='password' name='password' id='password' maxlength="50" placeholder="Password"/>
<br>
<input class="btn btn-lg btn-primary btn-block" type='button' name='submit' id="submission" value='Submit' />
</fieldset>
<!-- //container -->
</div>
<script type="text/javascript">
$(function(){
$("#submission").click(function(){
var $id = $("#username").val();
var $pass = $("#password").val();
var $msg = "";
var $srvmsg = "";
if($.trim($id).length === 0 ) $msg+="- Username is requried\n";
if($.trim($pass).length === 0 ) $msg+="- Password is required\n";
if($msg === ""){
$srvmsg = $.ajax({
type : 'post',
async : false,
data : {
"username" : $id,
"password" : $pass
},
url : "http://localhost/login"
}).done(function(data){
if(data.loggedIn === true){
window.location = "http://localhost/my-app/www/home.html";
} else {
alert("Error Username and Password Incorrect");
}
});
} else {
alert("Errors on the form : \n"+$msg);
}
});
});
</script>
为了提供帮助,这也是我的服务器端代码,我已经对此进行了测试,但希望它可以提供更好的解决方法。
服务器端代码:
session_start();
if(isset($_POST)){
$username = $_POST['username'];
$password = $_POST['password'];
$msg = array();
if ($username&&$password){
$connect = mysql_connect("127.0.0.1:8889","root","root") or die ('Couldnt Connect!!');
mysql_select_db("AppDatabase") or die ('Couldnt find DB');
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows !=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
$_SESSION['clientid'] = $row['user_id'];
}
if($username==$dbusername&&$password==$dbpassword)
{
$_SESSION["loggedIn"] = true;
$msg['loggedIn'] = true;
$msg['client_id'] = $_SESSION['clientid'];
$msg['message'] = "welcome!";
} else {
$msg['client_id'] = false;
$_SESSION["loggedIn"] = false;
$msg['loggedIn'] = false;
};
}else{
$msg['message'] = 'Username or Password entered incorrectly';
}
} else {
$msg['message'] = 'You have not entered username or password';
}
echo json_encode($msg);
}
更新
我添加了type : 'post',
,但我仍然收到同样的错误。我不确定$ srvmsg是否正在传递用户名和密码。
谢谢你的时间。