PHP从Ajax调用重定向 [英] PHP redirect from Ajax Call
问题描述
我正在使用Ajax(带有本机JavaScript)和php的组合来构建登录.
Im working with a combination of Ajax (with native JavaScript) and php to construct a login from.
发件人位于一个php文件(login.php)中.提交后,它将运行JS onlclick函数,该函数将表单数据发布到另一个验证表单数据的php文件中:
The from sits in a php file (login.php). When it gets submitted, it runs a JS onlclick function which posts the form data to another php file which validates the form data :
<input type="button" name="submit" value="Submit" onclick="JavaScript:xmlhttpPost('validator.php')"/>
validator.php的结果使用JavaScript在div中返回:
The results from validator.php are returned in a div using JavaScript:
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
最后,如果密码和用户名都正确,validator.php将像这样运行重定向:
Finally if the password and username are both correct, validator.php runs a redirect like this:
if ( // form data is valid ) {
header("Location: welcome.php");
}
但是,由于一切都通过ajax运行,因此导致"welcome.php"页面显示在原始登录页面的结果" div中.
However, because everything's running through ajax, this results in the "welcome.php" page being displayed in the "results" div on the original login page.
是否可以通过JavaScript发送重定向?
Is there a way to send a redirect via JavaScript instead?
推荐答案
我想出了一个可行的解决方案,代替了实际可行的答案.我不确定这是否是正确的方法,但是效果很好.
In lieu of an answer that actually works, I've figured out a workable solution. I'm not sure whether this is the correct way of doing this but it works well.
在我的validator.php中,当表单值正确时,我输入以下内容:
In my validator.php when the form values are correct I put the following:
if ( // form data is valid ) {
echo 'redirect';
}
然后,在我的登录页面上,当从php页面返回字符串时,我输入了以下内容:
Then, on my login page, when returning the string from the php page I put this:
function updatepage(str){
if (str.match(/redirect/)) {
window.location.replace('welcome.php');
}
else {
document.getElementById("result").innerHTML = str;
}
}
这个想法是,当validator.php确认登录凭据正确时,它将返回一个字符串.
The idea is that when validator.php confirms the login credentials are correct it returns a string.
如果该字符串与"redirect"匹配,则JavaScript将重定向页面.
If that string matches "redirect", JavaScript will redirect the page.
如果有人对此有任何意见,请发表评论.我觉得这是一个很好的解决方案.惊讶的是我没想到.
If anyone has any input on this, please comment. I feel this is a pretty good solution. Surprised I didn't think of it earlier.
这篇关于PHP从Ajax调用重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!