我有jQuery登录表单,其功能是检查用户验证。
这是JS:
$(document).ready(function()
{
$('#button_sign_in').click(function(){
console.log('login');
$.ajax({
url: "login",
type: "post",
data: $('#login_form').serialize(),
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
});
});
逻辑是,如果用户名或密码错误,按钮就会抖动。如果登录正确,则重定向到主页。
这是我的PHP函数:
require ("functions/_db_.php");
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
header('location:home.php');
}
现在的问题是:如果登录被更正,页面将不会重定向到主页。
有什么建议吗?
也许是因为您没有进行重定向本身?
success: function (data) {
//console.log('data:'+data);
if (data.user) {
$('#lblUsername').text(data.user.username);
window.location = '/home.php'; // redirect to the homepage
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
如果您通过AJAX将其发送到客户端,则使用头的PHP重定向将不起作用。在这种情况下,您必须使用JS在客户端重定向它。
保持您的PHP脚本如下
//Check your inputs against to mysql injections
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT username, password FROM t_users WHERE username='$username' && password='$password'");
$found = mysql_num_rows($query);
if ($found > 0)
{
$res='SUCCESS';
}
else
{
$res='ERROR';
}
$ary=array("status"=>$res);
echo json_encode($ary); //Json output - we are sending the assynchronus data in json format
和您的脚本
$.ajax
({
url: "login",
type: "post",
data: $('#login_form').serialize(),
dataType:'json', //We need ajax data in json type
success: function (data)
{
if (data.status=='SUCCESS') //status is proper of the json object, which we gave in php code in above script
{
window.location='home.php';
}
else
{
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
},
error: function (e) {
console.log('error:'+e);
}
});
if (data.user)
{
$('#lblUsername').text(data.user.username);
window.location = "home.php";
}
老兄,我认为问题出在PHP方面,而不是javascript。考虑到这一点,这是您的解决方案,而不是位置,这是位置
header('Location: http://www.example.com/');
文档
当您对php脚本进行AJAX调用时,调用header()
将不会在浏览器中加载新页面。您可以通过echo 'success/fail'
响应AJAX调用,并通过检查AJAX的success:
部分中的响应自行重定向到所需页面。不要忘记设置php会话,并在登录后要显示的页面中检查用户登录是否成功。因此,您在php中的代码将是,
if ($found > 0) {
//set session here
echo 'success';
}
else
echo 'fail';
在Ajax中,
success: function (data) {
if (data == 'success') {
window.location = "home_page.php";
}
else {
$('#button_sign_in').shake(4,6,700,'#CC2222');
$('#username').focus();
}
}
在您的主页php中,检查会话。