加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax / php标题:位置

发布时间:2020-12-16 02:49:59 所属栏目:百科 来源:网络整理
导读:我有一个带有Ajax登录表单的Bootstrap模式. 显示错误,一切正常,直到login.php的结果为header(‘Location:index.php’); 我处理这样的结果: var hr = new XMLHttpRequest(); // Set content type header information for sending url encoded variables in
我有一个带有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;
        }
    }

问题是登录成功后我得到了标题(‘Location:index.php’);响应index.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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读