简体   繁体   English

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

[英]Login page AJAX redirect doesnt work

I use php with ajax. 我用ajax使用php。

<?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    
**/
?>

The problem is that it does redirect, but leaves part of authorization page, and the result = is mixed profile + auth page 问题是它确实重定向,但保留了部分授权页面,结果=混合配置文件+ auth页面

When using AJAX, redirecting using header() will not work. 使用AJAX时,使用header()重定向将不起作用。

This is what will happen: 这将是会发生的事情:

  • Request is sent to your PHP page. 请求将发送到您的PHP页面。
  • You send back a redirect header with location. 您发回一个带位置的重定向标题。
  • Browser fetches the redirected page. 浏览器获取重定向的页面。
  • Contents of the redirected page is then passed to your XMLHttpRequest object. 然后将重定向页面的内容传递给XMLHttpRequest对象。

What you need to do is: 你需要做的是:

  • Determine if the request is ajax by checking to see if $_SERVER['HTTP_X_REQUESTED_WITH'] has the value of xmlhttprequest . 通过检查$_SERVER['HTTP_X_REQUESTED_WITH']是否具有xmlhttprequest的值来确定请求是否为ajax。 Most JS libraries will send this. 大多数JS库都会发送这个。
  • If it is not AJAX, redirect using header('Location: /') 如果它不是AJAX,则使用header('Location: /')重定向header('Location: /')
  • If it is AJAX, send back a JSON response with a location and status code for your javascript part to redirect, or echo('location.replace("\\")'); 如果是AJAX,请发回JSON响应,其中包含javascript部分的位置和状态代码以重定向或echo('location.replace("\\")');

If you are using AJAX call to the page as written above, using both header() and JavaScript to redirect won't work. 如果您正如上面所写使用AJAX调用页面,则使用header()JavaScript重定向将不起作用。 You need to use javascript in order to redirect page. 您需要使用javascript才能重定向页面。 Sample codes: 示例代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM