阿贾克斯/ PHP的标题:位置 [英] Ajax/php header:Location

查看:143
本文介绍了阿贾克斯/ PHP的标题:位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引导模式与阿贾克斯登录表单。 显示错误信息,一切工作得很好,直到结果从的login.php 标题(位置:的index.php');

I have a Bootstrap modal with an Ajax login form. Displaying errors and everything works just fine until the result from login.php is 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;
        }
    }

现在的问题是,当登录成功,我也得到了标题(位置:的index.php'); 响应的index.php div.status 。

有没有一种简单的方法来PHP的标题翻译在JavaScript重定向?

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

推荐答案

您可以检测,如果该请求是一个Ajax请求。如果是返回一个JSON对象,它具有所需的位置,否则做一个典型的PHP重定向。

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.

<?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");
    }
?>

一旦你获得了JSON对象回来使用的JavaScript重定向用户

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

document.location = json.location;

这篇关于阿贾克斯/ PHP的标题:位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆