提交后ajax表单重定向 [英] ajax form redirect after submit

查看:117
本文介绍了提交后ajax表单重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,提交表单后,我在重定向方面遇到了问题. 我正在使用简单的Ajax表单在div中显示登录错误.

Hello there i'm having problem with redirection after form has been submit. I'm using simple ajax form for displaying login errors in a div.

$(document).ready(function(){
$('#formlogin').on('submit', function (e) {

    $.ajax({
        type: 'POST', 
        url: 'login.php',
        data: $(this).serialize(),
        success: function(data) {
        $('div#ack').empty().append(data);

        } 

    });

    e.preventDefault();
});

问题是提交成功后,它不会重定向到"logged_in.php"

The problem is after submit success it doesn't redirect to "logged_in.php"

这是php登录.

if (empty($username) === true || empty ($password) === true)    {
    $errors [] = 'Please enter both username and password!';

} else if (user_exists($username) === false)   {
    $errors [] = 'We can not find the name. Have you registered?';
} else {

    $login = login($username, $password);
    if ($login === false)  {
        $errors [] = 'This user name or password is incorrect.';

    } else {

        $_SESSION['user_id'] = $login;
        header('Location: logged_in.php');  
        exit();

    }


}

推荐答案

如果您重定向使用AJAX调用的页面,它将重定向父页面.

If you redirect a page that was called with AJAX, it will not redirect the parent page.

您应该做的是回显表明用户已成功登录的信息.

What you should do is echo something that identifies that the user has successfully logged in.

也许您输入的不是header('Location: logged_in.php');:

echo "success";

然后,在您的成功功能中:

Then, in your success function:

success: function(data) {
    if (data == "success")
        window.location = "logged_in.php";
    else
        alert("Wrong password.");
}

请注意,ajax中的success并不意味着您已经成功登录,仅意味着对页面的请求返回了无错误(500).您仍然需要决定要如何处理数据.

Note that success in ajax does not mean that you have successfully logged in, just means that the request to the page returned without error (500). You still need to decide what you want to do with your data.

这篇关于提交后ajax表单重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆