php - Ajax/php header :Location

标签 php javascript jquery ajax twitter-bootstrap

我有一个带有 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/

相关文章:

php - 具有相同请求 header 的 BASH cURL 和 PHP cURL 的不同响应

PHP empty() 奇怪的行为

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

javascript - 为什么这个 RegExp 查询返回所有结果?

javascript - 未授权用户的单独页面或同一页面的不同配置?

javascript - 如何使用 jQuery 阻止鼠标离开太快而缩短背景图像转换

php - SEO 和 ajax 加载的内容链接

javascript - 逗号运算符返回

jquery - jQuery 没有使用 name 属性的选择器吗?如果是的话为什么?有什么可能的解决办法?

javascript - 完整日历选择 : callback Javascript Error