提问人:Dumebi 提问时间:9/6/2023 最后编辑:Dumebi 更新时间:9/8/2023 访问量:106
即使使用 session_start() 也无法访问会话变量
Can't access session variable even with session_start()
问:
我无法从一个页面访问我的会话变量到另一个页面。当我从将会话变量设置为常规 JSON 响应的页面访问响应时,我可以确认会话变量是否按要求设置。但是,当我使用 location.replace 导航到另一个页面时,我使用 PHP 会话start() 并且无法访问会话变量。我得到一个 $_SESSION 的空数组,当会话变量被回显时,没有输出任何值。我已经附加了设置会话变量的页面和尝试访问它的页面的代码。此外,我正在尝试在Apache服务器上运行代码,并从完全相同的域访问页面,所有文件都在同一位置。
我尝试遵循我在网上找到的会话变量的所有PHP规则,包括添加到第一页,这将变量
session_write_close();
并期望会话变量集在第二页上得到回显/访问。
设置会话变量的第一页:
<?php
session_start(); // Start the session
$_SESSION['display_page2'] = "true";
echo "The value of 'display_page2' is: " . $_SESSION['display_page2'];
?>
用于访问会话变量的第二个页面:
<?php
session_start();
var_dump($_SESSION); // Check the contents of the session array
echo "The value of 'display_page2' is: " . $_SESSION['display_page2'];
?>
第三页上的 AJAX 请求,该请求调用第一页以设置会话变量并重定向到第二页(在响应中,我能够验证会话变量是否按要求设置):
$.ajax({
type: "POST",
url: "https://url-to-api",
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function() {
$.ajax({
type: "POST",
url: "firstpage.php",
data: { display_page2: true },
success: function(response) {
alert(response);
location.replace("secondpage.php");
},
error: function() {
alert("Unsuccessful");
}
});
},
error: function() {
alert("Unsuccessful. Please try password again or request new password.");
location.reload();
},
});
答:
0赞
Simon
9/8/2023
#1
你的PHP看起来不错。
我以前没有在 jQuery 中实现过 ajax,但这里有一种方法可以用 vanilla javascript 来实现。
<div id="content">
</div>
<button onclick="nextPage();">Page 2</button>
<script>
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
document.getElementById("content").innerHTML = this.responseText;
}
// Send a request
xhttp.open("POST", "firstpage.php");
xhttp.send();
function nextPage() {
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
document.getElementById("content").innerHTML = this.responseText;
}
// Send a request
xhttp.open("POST", "secondpage.php");
xhttp.send();
}
</script>
评论