0

我有一个通过 PHP 处理的 HTML 表单,它是一个简单的登录脚本。这工作正常,但我想用 AJAX 捕捉错误。基本上,如果检查登录的 PHP 函数返回 false,它应该通过 jQuery 将该错误写入 DOM。但是,如果我使用 AJAX 捕获表单提交,它将阻止 PHP 文件进行重定向。我只想在 PHP 文件返回 false 时才停止表单重定向。任何帮助将非常感激。这是一些代码来说明我在说什么:

controller_login.js

$(document).ready(function(){

$('form.loginSubmit').on('submit',function(){


    var that = $(this),
        url=that.attr('action'),
        type=that.attr('method'),
        data={};

    that.find('[name]').each(function(index,value){ 
        var that=$(this), 
            name=that.attr('name'); 
            value=that.val(); 
            data[name]=value;
    });


    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response){
            errorHandle(response);

        }


    });

return false;

});


});

function errorHandle(error)
{
    console.log(error);
}

如果出现 PHP 错误,该文件最终将修改 DOM。目前,它只是记录。

checkLogin.php

if($verifySqlRequest==1){
    session_register("loginUsername");
    session_register("loginPassword");
    header("location:http://localhost/asd/dashboard.html");
    echo "login success!";  
}
else{
    echo "Wrong user name or password...";
}

这只是登录身份验证的一个片段,但本质上我希望将最后一个回显传达给controller_login.js,但如果登录成功通过身份验证,它应该继续重定向。任何帮助将不胜感激!,谢谢!

4

3 回答 3

2

浏览器不会响应来自 Ajax 调用的 302 或 301(重定向)。您仍然可以使用该代码进行响应,但是,您必须通过脚本手动处理重定向:

window.location.replace("http://localhost/asd/dashboard.html");
于 2013-09-18T03:18:01.313 回答
2

或者你可以这样做

> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';

 $.ajax({
url: url,
type: type,
data: data,
success: function(response){
    $('#response_element').html(response);

}
于 2013-09-18T03:32:54.843 回答
0

使用 Ajax 的目的是避免重新加载页面。如果用户将在登录时被重定向,您也可以同步提交表单并让 PHP 显示错误。

只是为了争论,如果你想做一个 Ajax 函数并显示从服务器返回的消息,你会这样做:

<?php 
echo 'this is the message'; 
?>

你会做

<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>

但是,您不能重定向并返回数据。

于 2013-09-18T03:34:58.560 回答