Ajax/php header:Location
Ajax/php header:Location
我有一个带有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 标头。 它将为用户提供与来自整页请求的传统重定向响应相同的基本体验。
相关文章:
- 正在使用$location.path(.)路由ng视图
- window.location替换并传递URL历史记录条目中的变量
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- location.reload(true)崩溃浏览器选项卡
- window.location使用jquery mobile实现chrome跳转
- CORS:否'访问控制允许来源'header-但是php设置头文件
- Windows.Open 在 window.Location 工作时不起作用
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 我可以使用location.href为变量生成url吗
- 如何将所有作业自定义到window.location.href
- window.location未刷新到现有URL
- 依次调用location.reload()和location.assign()
- 如果window.location.href.indexOf('player=1')添加样式
- 在$state.go之后执行$window.location.reload(true)
- javascript window.location在检查firebug时给了我一个错误的url路径
- 使用 php header('location') 刷新带有 javascript 的页面
- Ajax/php header:Location
- 有可能通过Javascript的Location: header来阻止浏览器重定向吗?
- 使用Javascript重定向页面,如PHP's Header->Location
- window.location(JS)与header()(PHP)用于重定向