PHP标头不会与AJAX重定向

时间:2012-12-04 01:20:10

标签: php javascript ajax rest header

对于项目,我们必须创建一个基本的登录系统。我试图使用REST来管理我的整个页面。现在我相信我在这里遗漏或误解了一些关键概念,但我一直试图弄清楚如何做到这一点。不允许在本练习中使用库,所以我不能使用JQuery。

所以继承我的问题:我有一个.js文件检查用户名长度和密码长度等....在这个.js文件中我还有一个ajax函数,它将用户名和电子邮件发送给PHP来验证目前还没有使用SQL的电子邮件或用户名的用户。

function checkUser()
        {
            var ajax = new Ajax(); // instantiates my external ajax class
            var email = document.getElementById("newEmail").value;
            var username = document.getElementById("newUserName").value
            ajax.post("index.php?method=register&check=check", "newEmail=" + email + "&newUserName=" + username, callbackCatch)

        }
    function callbackCatch(param)   
        {
            var responseMessages = JSON.parse(param.responseText);

            emailMessage = responseMessages.emailMessage;
            userNameMessage = responseMessages.userNameMessage;
            userEmailIsOk = responseMessages.userEmailIsOk;
            userNameIsOk = responseMessages.userNameIsOk;
            release = true;
            if((userEmailIsOk + userNameIsOk) != 2)
                {
                    console.log(userEmailIsOk + userNameIsOk);
                    release = false;
                }

            updateMessageFields();
        }

我得到一个JSON字符串,我将其解析,然后与我的表单值进行比较。当一切都找到并且花花公子时,我点击我的表单页面上的注册按钮,它将所有字段发布回我的php文件。但是,当我这样做时,我的外部ajax类每次都以某种方式被访问,我得到一个错误:NS_NOINTERFACE:Component没有请求的接口。

我假设因为每当我发帖时AJAX都在背景中运行,即使从我的表单中,它也会尝试发送回我的参数,在这种情况下它是不兼容的。

我不知道如何解决这个问题。我想要处理传输的PHP文件如下所示:

require_once("../database/table.php");

班级考试{

private $SQLtable;

private $newEmail;
private $newPswrd;
private $newUserName;
private $newFullName;


public function test()
    {
        $this->SQLtable = new table();
        $this->initClassVars();
        $this->generateUserName();
        $this->regUser();


    }
function initClassVars()
    {
        if(isset($_POST["newPassword"]))
            {
                $this->newPswrd = $_POST["newPassword"];
            }
        if(isset($_POST['newUserName']))
            {
                $this->newUserName = $_POST['newUserName'];
            }
        if(isset($_POST["newEmail"]))
            {
                $this->newEmail = $_POST["newEmail"];
            }
        if(isset($_POST["newFullName"]))
            {
                $this->newFullName = $_POST["newFullName"];
            }
    }
function generateUserName()
    {
        if(isset($_POST["newFullName"]))
        {
            $suggestedUserName = str_replace(" ", "", $this->newFullName);
            $this->newUserName = $suggestedUserName;
        }
    }

function regUser()
    {       

                $this->SQLtable->registerUser($this->newEmail, $this->newPswrd, $this->newFullName, $this->newUserName);
                $sessionKey = $this->genKey();
                $this->SQLtable->authUser($this->newEmail, $this->newPswrd, $sessionKey);
                header("location:Location:index.php?method=feed&key=$sessionKey&user=$this->newEmail");
                exit;
    }

function genKey($length = 16)
    {
        $options = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //Range
        $key = ""; //Empty holder for key
        for($i = 0; $i < $length; $i++)
            {
                $code = rand(0, strlen($options) - 1); 
                $key .= $options[$code];  // Loops through as long as the $length is set and adds a random string char from $options to build a new key.
            }
        return $key;
    }

}

正如您所见,我正在使用API​​密钥来控制身份验证。我还没有使用它的cookie,但是在我弄清楚如何对这个注册事项进行排序之后,这样做不好。

很抱歉,如果我不清楚。这是我关于stackoverflow的第一个问题,基本上我从未在我的生活中写过一行代码,直到大约8个月前,所以请耐心等待我的新代码:D。谢谢..

好的,这就是HTML和调用函数的地方: 这是我的表格html文件。 doctype和header是单独添加的,因为我经常使用它们几次。

<body>

<h1> Thanks! <!-- $user -->, you're almost there.  We just need a few more details      </h1>

<form id="registerUser" name="registerUser" action="index.php?method=test" method="post">
<p>
<label for="newFullName">Full Name: </label>
<input type="text" id="newFullName" name="newFullName" value="$newFullName" />
<span id="nameMessage"></span>
</p>
<p>
<label for="newUserName">User Name: </label>
<input type = "text" id="newUserName" name="NewUserName" value="$newUserName" />
<span id="nicknameMessage"><!-- $newUserNameMessage --></span>
</p>
<p>
<label for="newEmail">Email: </label>
<input type="text" id="newEmail" name="newEmail" value="$newEmail" />
<span id = "newEmailMessage"><!-- $newEmailMessage --></span>
</p>
<p>
<label for ="newPassword">Password: </label>
<input type="password" id="newPassword" name="newPassword" value="$newPswrd" />
<span id = "newPasswordMessage"></span>
</p>
<input type="submit" id="register" disabled="disabled" value="Register" onclick=""/>
</form>


<p><a href="../../../Index.html"> Click here to go back to the login site and login.   </a></p>

<script type="text/javascript" language="javascript" src="../../js/net/ajaxHandler.js">    </script>
<script type="text/javascript" language="javascript">var bootstrap = new ajaxHandler();     bootstrap.init(); </script>
</body>
</html>

整个JS文件都是这个..它有点乱,但它因为我一直在玩弄它:

var ajaxHandler = function()
{
    var self = this;
    var release = true;
    var nameField;
    var userField;
    var emailField;
    var passWordField
    var emailMessage;
    var userNameMessage;

    self.init = function()
        {
            addEventListeners();
            checkFormForErrors();
        }

    self.redirect = function ()
        {
        }
    function addEventListeners()
        {
            nameField       = document.getElementById("newFullName");
            userField       = document.getElementById("newUserName");
            emailField      = document.getElementById("newEmail");
            passWordField   = document.getElementById("newPassword");

            Event.addEventListener(nameField, 'click', checkFormForErrors);
            Event.addEventListener(userField, 'click', checkUser);
            Event.addEventListener(emailField, 'click', checkUser);
            Event.addEventListener(passWordField, 'click', checkFormForErrors);

            Event.addEventListener(nameField, 'keyup', checkFormForErrors);
            Event.addEventListener(userField, 'keyup', checkUser);
            Event.addEventListener(emailField, 'keyup', checkUser);
            Event.addEventListener(passWordField, 'keyup', checkFormForErrors);
        }

    function checkPassword()
        {
        var passWordIsOk;
        var patt        = /\s/;
        var whiteSpace  = patt.test(passWordField);
        var passwordLength = passWordField.value.length;
        if (passwordLength < 8 )
            {
                document.getElementById("newPasswordMessage").innerHTML = "Your passowrd must be at least 8 charachters long. ";
                passWordIsOk = false
                if (whiteSpace)
                    {
                        document.getElementById("newPasswordMessage").innerHTML += "Your Password cannot contain any spaces.";
                        passWordIsOk = false
                    }
            } 
        else
            {
                document.getElementById("newPasswordMessage").innerHTML = "Password looks good";
                passWordIsOk = true
            }
        return passWordIsOk;
        }

    function checkName()    
        {
            var userNameIsOk;
            var nameMessage = document.getElementById("nameMessage");
            if (!nameField.value)
                {
                    nameMessage.innerHTML = "You need to enter a name."
                    userNameIsOk = false;

                }
            else
                {
                    nameMessage.innerHTML = "Name looks great."
                    userNameIsOk = true;
                }
            return userNameIsOk;
        }

    function checkEmailSyntax()
        {
            var EmailIsOk = true
            var patt    = /^([\w!.%+\-])+@([\w\-])+(?:\.[\w\-]+)+$/ ;
            var format  = patt.test(emailField.value);
            if (!format)
                {
                    document.getElementById("newEmailMessage").innerHTML = "Your email does not appear to be in the right format."
                    EmailIsOk = false;
                }
            return EmailIsOk        
        }

    function checkFullNameSyntax()
        {
            var nameIsOk = true
            if (document.getElementById("newUserName").value == "")
                {
                    document.getElementById("nicknameMessage").innerHTML = "You must enter a username.  You can always change it later."
                    nameIsOk = false
                }
            return nameIsOk;
        }

    function checkUser()
        {
            var ajax = new Ajax();
            var email = document.getElementById("newEmail").value;
            var username = document.getElementById("newUserName").value
            ajax.post("index.php?method=register&check=check", "newEmail=" + email + "&newUserName=" + username, callbackCatch)

        }
    function callbackCatch(param)   
        {
            var responseMessages = JSON.parse(param.responseText);

            emailMessage = responseMessages.emailMessage;
            userNameMessage = responseMessages.userNameMessage;
            userEmailIsOk = responseMessages.userEmailIsOk;
            userNameIsOk = responseMessages.userNameIsOk;
            release = true;
            if((userEmailIsOk + userNameIsOk) != 2)
                {
                    console.log(userEmailIsOk + userNameIsOk);
                    release = false;
                }

            updateMessageFields();
            var ajax = "";
        }
    function updateMessageFields()
        {
            document.getElementById("nicknameMessage").innerHTML = userNameMessage;
            document.getElementById("newEmailMessage").innerHTML = emailMessage;
            checkFormForErrors();

        }
    function checkFormForErrors()
        {
            console.log('hi');
            var nameOk = checkFullNameSyntax()
            console.log(nameOk);
            var passOk = checkPassword()
            console.log(passOk);
            var userOk = checkName()
            console.log(userOk);    
            var emailOk = checkEmailSyntax()
            console.log(emailOk);
            console.log(release);
            document.getElementById("register").disabled = true;
            if(release && nameOk && passOk && userOk && emailOk)
                {
                    console.log('hey');
                    console.log(release && nameOk && passOk && userOk && emailOk)
                    document.getElementById("register").disabled = false;
                }
        }
}

2 个答案:

答案 0 :(得分:2)

我不知道这是否难以理解,但是当你的AJAX收到响应时,页面已被重定向...而且你的AJAX看起来很正常 - 它得到了回复(在这种情况下,一个完整的页面,而不是JSON)。这是事件的顺序:

AJAX Request

--> Browser sends request to PHP file

----> Your PHP file receives the request, processes it, and "redirects"

<---- HTTP 302 status code sent to browser

<-- Browser receives 302 status code, redirects response, and returns result as AJAX response

至少我很确定会发生什么 - 我发誓之前我遇到过这个“问题”,我发现这就是发生的事情。

要“修复”这个,你有几个选择。您可以在JSON中发送此信息,而不是使用PHP来“重定向”。然后,在你的回调中,你可以检查它的存在......就像一个“重定向”键,并使用它的值重定向到(在PHP中将其值设置为重定向到的URL)。或者,您可以将其保留为字符串,在解析之前,请从“redirect:”开始检查它。如果以此开头,则获取字符串的其余部分并重定向到该值(将其值设置为PHP中的重定向到的URL)。否则,像JSON一样解析它并正常处理它。

答案 1 :(得分:1)

你无法在ajax调用中从php重定向。

您需要将正确的信息从您的php脚本发送回您的javascript并使用您从php返回的参数从那里进行重定向。

你的php中也有一个Location:太多,但这不是问题所在。