我有一个带有 Ajax 登录表单的 Bootstrap 模式。
显示错误并且一切正常,直到 login.php 的结果是 header('Location: index.php');
我这样处理结果:
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;
}
}
问题是当登录成功并且我得到 header('Location: index.php');
响应 index.php is opened in div.status
.
有没有一种简单的方法可以将 PHP header 转换为 javascript 中的重定向?
最佳答案
您可以检测请求是否为 ajax 请求。如果它返回一个具有所需位置的 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");
}
?>
一旦你在 javascript 中返回 json 对象,使用
重定向用户document.location = json.location;
关于php - Ajax/php header :Location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18745669/