我有一个带有Ajax登录表单的引导模式。显示错误,一切正常,直到登录结果.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');
响应索引时.php在div.status
中打开。
有没有一种简单的方法可以将 PHP 标头转换为 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;
你应该使用 javascript 重写document.location
,而不是发送 HTTP 标头。 它将为用户提供与来自整页请求的传统重定向响应相同的基本体验。