Php 登录页面AJAX重定向不起作用

Php 登录页面AJAX重定向不起作用,php,ajax,Php,Ajax,我使用php和ajax <?php /* * Suppose, user has entered both correct login and password * then server response is TO **REDIRECT** to profile page * / header('location:/'); /* * * print <<<HTML <scrpit> window . location = '/profile.php'

我使用php和ajax

<?php
/*
* Suppose, user has entered both correct login and password
* then server response is TO **REDIRECT** to profile page
* 
/
 header('location:/');
/*
* 
* print <<<HTML
<scrpit> window . location = '/profile.php';</script>
HTML;
* also doesnt work    
**/
?>


问题是它确实重定向了,但留下了授权页面的一部分,结果=是混合配置文件+身份验证页面当使用AJAX时,使用
header()
重定向将不起作用

这就是将要发生的事情:

  • 请求被发送到您的PHP页面
  • 您发送回一个带有位置的重定向头
  • 浏览器获取重定向页面
  • 重定向页面的内容随后被传递到XMLHttpRequest对象
您需要做的是:

  • 通过检查
    $\u服务器['HTTP\u X\u REQUESTED\u WITH']
    的值是否为
    xmlhttprequest
    来确定请求是否为ajax。大多数JS库都会发送此消息
  • 如果不是AJAX,则使用
    头('Location:/')重定向
  • 如果是AJAX,则返回一个JSON响应,其中包含要重定向的javascript部分的位置和状态代码,或者
    echo('location.replace(“\”)

如果您像上面写的那样使用AJAX调用页面,那么同时使用
header()
JavaScript
重定向将不起作用。您需要使用javascript来重定向页面。示例代码:

<?php
    /**
     * Suppose, user has entered both correct login and password
     * then server response is TO **REDIRECT** to profile page
     */

    // define login is false by default
    $response = array();
    response['Success'] = false;

    // use if-condition to check if succeeded
    // then assign it to true like this
    response['Success'] = true;
    die( json_encode($response) );
?>

    // Javascript Code:

    // You must decode it first since it's json
    // Assuming that `theResponse` is the message callback
    var responseStr = JSON.parse( theResponse );
    if ( responseStr.Success ){
        location.href = 'profile.php';
    }else {
        // show some message
    }

//Javascript代码:
//您必须首先解码它,因为它是json
//假设'theResponse'是消息回调
var responsest=JSON.parse(响应);
如果(响应成功){
location.href='profile.php';
}否则{
//显示一些消息
}

那么您是说已经使用ajax提交了一个表单,并试图用PHP控制器重定向用户?只需在回调中传回重定向url,并让js重定向。。。