繁体   English   中英

ajax登录表单,重新加载到表单而不是页面上

[英]ajax login form, reloading onto the form rather than page

所以我有一个登录表单,在其中我使用ajax从我的login.php捕获登录错误(例如“密码错误”),并将其显示在相同的登录表单上,而不是重新加载带有错误消息的新页面。 现在可以正常工作,但是登录成功后,它会将整个已登录页面加载到登录表单上,而不是将其加载到整个页面上! 您可以在下图中看到。 登录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>

谁能看到这里的问题吗? 谢谢

这是因为您的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){}中设置了一个断点,则发现成功时info具有urlRedirect属性。 并且在失败时,您会发现info只是带有html数据的常规字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM