twitter-bootstrap Ajax/php 标头:位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18745669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 18:20:49  来源:igfitidea点击:

Ajax/php header:Location

phpjavascriptjqueryajaxtwitter-bootstrap

提问by justanotherhobbyist

I have a Bootstrap modal with an Ajax login form. Displaying errors and everything works just fine until the result from login.phpis header('Location: index.php');

我有一个带有 Ajax 登录表单的 Bootstrap 模式。显示错误并且一切正常,直到login.php的结果为 header('Location: index.php');

I handle the result like this:

我处理这样的结果:

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;
        }
    }

The problem is that when the login is successful and I get the header('Location: index.php');response index.phpis opened in div.status.

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

Is there an easy way to translate the PHP header to a redirect in javascript?

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

回答by Logan Murphy

You can detect if the request is an ajax request. If it is return a json object that has the desired location otherwise do a typical php redirect.

您可以检测请求是否是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");
    }
?>

Once you get the json object back in javascript redirect the user using

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

document.location = json.location;

回答by Teddy

You should use javascript to rewrite the document.locationinstead of sending a HTTP header. It will give the user the same basic experience as a traditional redirect response from a full page request.

您应该使用 javascript 来重写document.location而不是发送 HTTP 标头。它将为用户提供与来自整页请求的传统重定向响应相同的基本体验。