2016-03-27 27 views
0

所以我有一个登录表单,我使用ajax从login.php中捕获登录错误,即“不正确的密码”,并将它们显示在相同的登录表单上比重新加载错误消息的新页面。现在工作正常,但是当登录成功时,它现在将整个登录页面加载到登录表单上,而不是将其加载到整个页面!您可以在下面的图片中看到。 login ajax error 这里是我的Ajax代码:ajax登录表单,重新加载到表单上而不是页面

$("#login_button").click(function(){ 

    $.post($("#login_form").attr("action"), $("#login_form :input").serializeArray(), function(info){$("#login_errors").html(info);}); 
    // Prevent the default action from occurring. 
    return false; 
}); 

$("login_form").submit(function(){ 
    return false; 
}); 

这里是我为我的登录表单代码:

<form id= "login_form" action="login.php" method="post"> 
    <span id="login_errors" style="color:#F00;"></span> 
    <label>Email Address</label> 
    <input type="text" name="email" id="email" required="required"/> 
    <br /> 

    <label>Password</label> 
    <input type="password" name="password" id="password" required="required"/> 
    <br /> 

    <div class="checkbox"> 
    <input id="remember" type="checkbox" name="keep" /> 
    <label for="remember">Keep me signed in</label> 
    </div> 

    <div class="action_btns"> 
    <div class="one_half last"><input type="submit" class="btn btn-blue" id="login_button" value="Login"></div> 
    <div class="one_half last"><a href="#" id="register_form" class="btn">Sign up</a></div> 
    </div> 
</form> 

任何人都可以看到的问题是什么吗? 谢谢

回答

1

这是因为你的ajax回调每次都做同样的事情。无论返回什么,它都会进入$("#login_errors").html()

如果你成功了,你可能想要做的是发回带有页面url的json。然后,你可以做这样的事情:

$.post($("#login_form").attr("action"), 
    $("#login_form :input").serializeArray(), 
    function(info){ 
    if(info.urlRedirect!=null) 
     window.location.href = info.urlRedirect; 
    else $("#login_errors").html(info); 
    }); 

要做到这一点,你就需要修改php服务器端组件做这样的事情:

<?php 
$success = $_REQUEST['s']; 
if($success) { 
    header('Content-type: application/json'); 
    echo json_encode(array('urlRedirect'=> '/home.php')); 
} else { 
    echo "<div>wrong username or password - please try again</div>"; 
} 
?> 

这只是说明如何样本如果登录成功,则返回带有URL的JSON;如果登录失败,则返回一个html字符串(这将是您的登录表单)。

如果你这样做,你设置你的JavaScript您function(info){}内部的断点,你会发现成功,infourlRedirect属性。如果失败,您会发现info只是一个包含html数据的常规字符串。

+0

我试过你的代码,但现在它再次加载login.php:/ – rockb0ttom

+0

为什么会发生这种情况? – rockb0ttom

+0

没有更多信息就无法分辨。什么是你的PHP页面成功登录传回?它是一个JSON,urlRedirect的价值是什么? – David784

相关问题