PHP头不会与AJAX重定向 [英] PHP header wont redirect with AJAX

查看:126
本文介绍了PHP头不会与AJAX重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的一个项目,我们必须建立一个基本的登录系统。我试着去使用REST来管理我的整个页面。现在我相信林丢失或误解这里的一些关键概念,但我一直在试图找出如何做到这一点的年龄。不允许使用库这个练习,所以我不能使用JQuery。

所以,我的继承人问题:我有一个检查用户名长度和密码长度等.js文件....这个js文件我也有一个Ajax功能将用户名和电子邮件到PHP验证有没有与该电子邮件或用户名使用SQL的现有用户。

 函数checkUser()
        {
            VAR阿贾克斯=新的Ajax(); //实例化我的外部AJAX类
            VAR电子邮件=的document.getElementById(NEWEMAIL)值。
            变种的用户名=的document.getElementById(newUserName)。值
            ajax.post(的index.php方法=注册和放大器;检查=检查,NEWEMAIL =+电子邮件+&放大器; newUserName =+用户名,callbackCatch)

        }
    功能callbackCatch(参数)
        {
            VAR responseMessages = JSON.parse(param.responseText);

            emailMessage = responseMessages.emailMessage;
            userNameMessage = responseMessages.userNameMessage;
            userEmailIsOk = responseMessages.userEmailIsOk;
            userNameIsOk = responseMessages.userNameIsOk;
            释放= TRUE;
            如果((userEmailIsOk + userNameIsOk)!= 2)
                {
                    的console.log(userEmailIsOk + userNameIsOk);
                    释放= FALSE;
                }

            updateMessageFields();
        }
 

我得到一个JSON字符串回我分析,然后比较对我的表单值。当一切都觉得,很正常,我点击我的表单页面注册按钮其职位的所有字段回到我的PHP文件。但是看来,当我这样做我的外部阿贾克斯类不知何故每次访问,我得到一个错误:NS_NOINTERFACE:组件没有请求的接口。

林假设,因为AJAX是在化背景下运行的,每当我做一个帖子,甚至从我的形式,它试图发送回我的参数,在这种情况下,是不兼容的。

我不知道如何解决这个问题。这是假设办理过户我的PHP文件看起来是这样的:

  require_once(../数据库/ table.php);
 

类的测试{

 私人$ SQLTABLE;

私人$ NEWEMAIL;
私人$ newPswrd;
私人$ newUserName;
私人$ newFullName;


公共功能测试()
    {
        $这个 - > SQLTABLE =新表();
        $这个 - > initClassVars();
        $这个 - > generateUserName();
        $这个 - > regUser();


    }
功能initClassVars()
    {
        如果(使用isset($ _ POST [新密码]))
            {
                $这个 - > newPswrd = $ _ POST [新密码];
            }
        如果(使用isset($ _ POST ['newUserName']))
            {
                $这个 - > newUserName = $ _ POST ['newUserName'];
            }
        如果(使用isset($ _ POST [NEWEMAIL]))
            {
                $这个 - > NEWEMAIL = $ _ POST [NEWEMAIL];
            }
        如果(使用isset($ _ POST [newFullName]))
            {
                $这个 - > newFullName = $ _ POST [newFullName];
            }
    }
功能generateUserName()
    {
        如果(使用isset($ _ POST [newFullName]))
        {
            $ suggestedUserName = str_replace函数(,,$这 - > newFullName);
            $这个 - > newUserName = $ suggestedUserName;
        }
    }

功能regUser()
    {

                $这个 - > SQLtable-> registerUser($这个 - > NEWEMAIL,$这个 - > newPswrd,$这个 - > newFullName,$这个 - > newUserName);
                $ sessionKey = $这个 - > genKey();
                $这个 - > SQLtable-> AUTHUSER($这个 - > NEWEMAIL,$这个 - > newPswrd,$ sessionKey);
                标题(?位置:位置:index.php的方法=饲料和放大器;关键= $ sessionKey和放大器;用户= $这个 - > NEWEMAIL);
                出口;
    }

功能genKey($长度= 16)
    {
        $选项=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789; //范围
        $关键=;关键//空架
        为($ i = 0; $ I< $长度; $ I ++)
            {
                $code =兰特(0,strlen的($选项) -  1);
                。$键= $选项[$code];经过长达//环路为$长度设置,并增加了一个随机字符串CHAR从$选项,以建立一个新的密钥。
            }
        返回$关键;
    }
 

}

正如你所看到的林玩弄周围使用API​​密钥来控制认证。我还没有得到它的工作还没有饼干,但生病做到这一点后,我找出如何得到这个注册的事情进行排序。

如果我一直不清楚对不起。这是我对计算器的第一个问题,基本上我从来没有写过一行code在我的生活,直到8个月前我newbish code所以熊:D。谢谢..

确定这样继承人的HTML和那里的功能也被称为: 这是我的表格的HTML文件。文档类型和头分别加入我一遍又一遍几次使用它们。

 <身体GT;

< H1>谢谢! <! -  $用户 - >中你几乎没有。我们只是需要更多的一些细节和LT; / H1>

<形式ID =registerUserNAME =registerUser行动=?index.php的方法=测试方法=邮报>
&其中p为H.;
<标签=newFullName>全名:LT; /标签>
<输入类型=文本ID =newFullNameNAME =newFullName值=$ newFullName/>
&所述;跨度的id =nameMessage>&所述; /跨度>
&所述; / P>
&其中p为H.;
<标签=newUserName>用户名:​​LT; /标签>
<输入类型=文本ID =newUserNameNAME =NewUserName值=$ newUserName/>
<跨度ID =nicknameMessage><! -  $ newUserNameMessage  - >< / SPAN>
&所述; / P>
&其中p为H.;
<标签=NEWEMAIL>电子邮件:LT; /标签>
<输入类型=文本ID =NEWEMAILNAME =NEWEMAIL值=$ NEWEMAIL/>
<跨度ID =newEmailMessage><! -  $ newEmailMessage  - >< / SPAN>
&所述; / P>
&其中p为H.;
<标签=新密码>密码:LT; /标签>
<输入类型=密码ID =新密码NAME =新密码值=$ newPswrd/>
&所述;跨度的id =newPasswordMessage>&所述; /跨度>
&所述; / P>
<输入类型=提交ID =注册禁用=禁用值=注册的onclick =/>
< /形式GT;


&其中p为H.;&所述; A HREF =../../../的index.html>点击此处返回到登录的网站和登录。 &所述; / a取代;&所述; / P>

<脚本类型=文/ JavaScript的LANGUAGE =JavaScript的SRC =../../ JS / NET / ajaxHandler.js> < / SCRIPT>
<脚本类型=文/ JavaScript的LANGUAGE =JavaScript的> VAR引导=新ajaxHandler(); bootstrap.init(); < / SCRIPT>
< /身体GT;
< / HTML>
 

整个JS文件是这样的..它有点混乱,但它因为伊夫一直与它玩弄了这么多:

  VAR ajaxHandler =功能()
{
    无功自我=这一点;
    变种版本=真;
    VAR为nameField;
    VAR userField;
    VAR emailField;
    VAR passWordField
    VAR emailMessage;
    VAR userNameMessage;

    self.init =功能()
        {
            addEventListeners();
            checkFormForErrors();
        }

    self.redirect =功能()
        {
        }
    功能addEventListeners()
        {
            为nameField =的document.getElementById(newFullName);
            userField =的document.getElementById(newUserName);
            emailField =的document.getElementById(NEWEMAIL);
            passWordField =的document.getElementById(新密码);

            Event.addEventListener(为nameField,咔哒,checkFormForErrors);
            Event.addEventListener(userField,点击,checkUser);
            Event.addEventListener(emailField,点击,checkUser);
            Event.addEventListener(passWordField,点击,checkFormForErrors);

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

    功能checkPassword()所在
        {
        VAR passWordIsOk;
        VAR PATT = / \ S /;
        VAR空白符= patt.test(passWordField);
        VAR passwordLength = passWordField.value.length;
        如果(passwordLength&所述; 8)
            {
                的document.getElementById(newPasswordMessage)的innerHTML =您passowrd必须至少为8 charachters长。。
                passWordIsOk = FALSE
                如果(或空格)
                    {
                        。的document.getElementById(newPasswordMessage)的innerHTML + =您的密码不能包含空格。;
                        passWordIsOk = FALSE
                    }
            }
        其他
            {
                的document.getElementById(newPasswordMessage)的innerHTML =密码看起来不错。
                passWordIsOk =真
            }
        返回passWordIsOk;
        }

    功能检查名()
        {
            VAR userNameIsOk;
            变种nameMessage =的document.getElementById(nameMessage);
            如果(!nameField.value)
                {
                    nameMessage.innerHTML =您需要输入一个名字。
                    userNameIsOk = FALSE;

                }
            其他
                {
                    nameMessage.innerHTML =名称看起来很棒。
                    userNameIsOk = TRUE;
                }
            返回userNameIsOk;
        }

    功能checkEmailSyntax()
        {
            VAR EmailIsOk =真
            VAR PATT = /^([\w!.%+\-])+@([\w\-])+(?:\.[\w\-]+)+$/;
            VAR格式= patt.test(emailField.value);
            如果(!格式)
                {
                    的document.getElementById(newEmailMessage)。innerHTML的=您的电子邮件不会出现在正确的格式。
                    EmailIsOk = FALSE;
                }
            返回EmailIsOk
        }

    功能checkFullNameSyntax()
        {
            VAR nameIsOk =真
            如果(的document.getElementById(newUserName)。价值==)
                {
                    的document.getElementById(nicknameMessage)。innerHTML的=你必须输入用户名,您可以随时进行更改。
                    nameIsOk = FALSE
                }
            返回nameIsOk;
        }

    功能checkUser()
        {
            VAR阿贾克斯=新的Ajax();
            VAR电子邮件=的document.getElementById(NEWEMAIL)值。
            变种的用户名=的document.getElementById(newUserName)。值
            ajax.post(的index.php方法=注册和放大器;检查=检查,NEWEMAIL =+电子邮件+&放大器; newUserName =+用户名,callbackCatch)

        }
    功能callbackCatch(参数)
        {
            VAR responseMessages = JSON.parse(param.responseText);

            emailMessage = responseMessages.emailMessage;
            userNameMessage = responseMessages.userNameMessage;
            userEmailIsOk = responseMessages.userEmailIsOk;
            userNameIsOk = responseMessages.userNameIsOk;
            释放= TRUE;
            如果((userEmailIsOk + userNameIsOk)!= 2)
                {
                    的console.log(userEmailIsOk + userNameIsOk);
                    释放= FALSE;
                }

            updateMessageFields();
            VAR阿贾克斯=;
        }
    功能updateMessageFields()
        {
            的document.getElementById(nicknameMessage)的innerHTML = userNameMessage。
            的document.getElementById(newEmailMessage)的innerHTML = emailMessage。
            checkFormForErrors();

        }
    功能checkFormForErrors()
        {
            的console.log('喜');
            VAR nameOk = checkFullNameSyntax()
            执行console.log(nameOk);
            VAR passOk = checkPassword()所在
            执行console.log(passOk);
            VAR userOk =检查名()
            执行console.log(userOk);
            VAR emailOk = checkEmailSyntax()
            执行console.log(emailOk);
            执行console.log(释放);
            的document.getElementById(注册)禁用= TRUE。
            如果(释放和放大器;&安培; nameOk和放大器;&安培; passOk和放大器;&安培; userOk和放大器;&安培; emailOk)
                {
                    的console.log('嗨');
                    的console.log(释放和放大器;&安培; nameOk和放大器;&安培; passOk和放大器;&安培; userOk和放大器;&安培; emailOk)
                    的document.getElementById(注册)禁用= FALSE。
                }
        }
}
 

解决方案

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

  AJAX请求

 - >浏览器发送请求到PHP文件

---->你的PHP文件接收请求,处理它,和重定向

< ---- HTTP 302状态code发送到浏览器

<  - 浏览器收到302状态code,重定向响应,并返回结果为Ajax响应
 

至少我pretty的肯定,这会发生什么 - 我发誓,我以前就遇到了这个问题,而我发现这是发生了什么事

要修理这个,你有几种选择。而不是使用PHP来重定向,你可以在你的JSON发送此信息。然后,在你的回调,你可以检查它的存在......就像一个重定向键,并用它的值来重定向到(它设置在PHP中的价值,以重定向到URL)。或者,你可以把它作为一个字符串,你解析它之前,检查它以重定向。如果它与启动时,得到的字符串的其余部分,并重定向到值(设置其在PHP值作为重定向到URL)。否则,解析它像JSON和正常处理它。

For a project we have to create a basic log in system. Im trying to use REST to manage my entire page. Now I believe Im missing or misunderstanding some key concept here but I've been trying to figure out how to do this for ages. Were not allowed to use libraries for this exercise so I cant use JQuery.

So heres my problem: I have a .js file that checks for username length and password length and etc.... in this .js file I also have an ajax function that sends the username and email to PHP to verify that there is not already an existing user with that email or username using 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();
        }

I get a JSON string back which I parse and then compare against my form values. When everything is find and dandy i click the register button on my form page which posts all the fields back to my php file. However it seems that when i do this my external ajax class is accessed somehow every time and I get an error : NS_NOINTERFACE: Component does not have requested interface.

Im assuming that because AJAX is running in the backgroud whenever I make a post, even from my form it tries to send back my param which in this case are not compatible.

I dont know how to fix this. My PHP file that is suppose to handle the transfer looks like this:

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

class test {

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;
    }

}

As you can see Im toying around with using an API key to control authentication. I havent gotten the cookies working with it yet, but ill do that after I figure out how to get this registration thing sorted.

Sorry if ive been unclear. This is my first question on stackoverflow and basically I never wrote a line of code in my life until about 8 months ago so bear with my newbish code :D. Thanks..

Ok so heres the HTML and where the functions are being called: This is my form html file. The doctype and header are added separately as I use them over and over a few times.

<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>

The entire JS file is this.. its a bit messy but its because Ive been toying with it so much:

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;
                }
        }
}

解决方案

I don't know if this will be hard to understand, but by the time your AJAX receives the response, the page has already been redirected...and to your AJAX, it looks normal - it's getting a response back (in this case, a full page, not JSON). This is the order of events:

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

At least I'm pretty sure that's what happens - I swear I've ran into this "problem" before, and I found out this is what was happening.

To "fix" this, you have a few options. Instead of using PHP to "redirect", you could send this information in your JSON. Then, in your callback, you could check for its existence...like a "redirect" key, and use its value to redirect to (setting its value in PHP as the URL to redirect to). Or, you could keep it as a string, and before you parse it, check for it starting with "redirect:". If it starts with that, get the rest of the string and redirect to that value (settings its value in PHP as the URL to redirect to). Otherwise, parse it like JSON and process it normally.

这篇关于PHP头不会与AJAX重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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