【发布时间】:2021-12-04 00:49:37
【问题描述】:
我正在使用 google 登录,并且大部分时间都在那里。用户成功登录,我可以访问我的 mysql 用户表来查找用户记录。 在完成用户处理并设置 $_SESSION 变量后,我想从 POST 页面重定向回我的 index.php 页面。我知道 POST 页面正在执行,但重定向不起作用,我没有看到任何错误(例如“无法修改标头信息 - 标头已发送”。
login.php包含google登录按钮,调用includes/oauth.js中的js函数
...
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="includes/oauth.js"></script>
</head>
<body>
<div id="content">
<div class="g-signin2" data-longtitle="true" data-onsuccess="onSignIn"></div>
...
onSignIn 函数负责登录过程并检索用户详细信息。它还准备包含身份验证令牌的 POST 调用
...
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/oauth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('idtoken=' + id_token);
...
includes/oauth.php 文件获取令牌,对其进行验证。获取 userId,在我的数据库中查找它并准备会话变量。此时,它应该重定向,但没有。我难住了。这是因为我在 POST 中使用了 XMLHttpRequest() 吗?
<?php
session_start();
...
if (isset($_POST['idtoken'])){
...
$_SESSION["auth"] = true;
$_SESSION["userId"] = $row['id'];
$_SESSION["userName"] = $row['name'];
header("Location: ../index.php");
exit();
}
...
【问题讨论】:
-
由于您使用的是 AJAX,重定向只会导致
index.php的内容返回为xhr.responseText,它不会让浏览器打开 URL。 -
只有当您在表单提交后重定向时,浏览器才会打开新的 URL。
-
我原以为这可能与xhr有关,实际上我在调试过程中确实注意到了xhr.response.Text中的网页内容。
-
实际执行重定向需要哪些选项?
-
在
xhr.onreadystatechange函数中,使用window.location = "../index.php"
标签: php post redirect google-signin