Ajax/php标题:位置

jus*_*ist 4 javascript php ajax jquery twitter-bootstrap

我有一个带有Ajax登录表单的Bootstrap模式.显示错误信息,一切工作就好了,直到从结果的login.phpheader('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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,当登录成功并且我得到header('Location: index.php');响应index.php被打开div.status.

有没有一种简单的方法将PHP标头转换为javascript中的重定向?

Log*_*phy 6

您可以检测请求是否是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");
    }
?>
Run Code Online (Sandbox Code Playgroud)

一旦你在javascript中重新获得json对象,用户就会重定向

document.location = json.location;
Run Code Online (Sandbox Code Playgroud)