[英]Ajax/php header:Location
I have a Bootstrap modal with an Ajax login form. 我有一个带有Ajax登录表单的Bootstrap模式。 Displaying errors and everything works just fine until the result from login.php is
header('Location: index.php');
显示错误,一切正常,直到login.php的结果为
header('Location: index.php');
I handle the result like this: 我处理这样的结果:
var hr = new XMLHttpRequest();
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
The problem is that when the login is successful and I get the header('Location: index.php');
问题是登录成功后我得到了
header('Location: index.php');
response index.php is opened in div.status
. 响应index.php在
div.status
打开。
Is there an easy way to translate the PHP header to a redirect in javascript? 有没有一种简单的方法将PHP标头转换为javascript中的重定向?
You can detect if the request is an ajax request. 您可以检测请求是否是ajax请求。 If it is return a json object that has the desired location otherwise do a typical php redirect.
如果它返回一个具有所需位置的json对象,否则执行典型的php重定向。
<?php
function isAjax() {
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if(isAjax()) {
echo json_encode(array("location" => "index.php"));
} else {
header("Location: index.php");
}
?>
Once you get the json object back in javascript redirect the user using 一旦你在javascript中重新获得json对象,用户就会重定向
document.location = json.location;
You should use javascript to rewrite the document.location
instead of sending a HTTP header. 您应该使用javascript重写
document.location
而不是发送HTTP标头。 It will give the user the same basic experience as a traditional redirect response from a full page request. 它将为用户提供与完整页面请求的传统重定向响应相同的基本体验。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.