在访问另一个网页中的会话变量时遇到一些问题
我尝试使用jquery刷新创建会话的页面(data.php),数据库连接和sql查询也可以正常工作,并对其进行了独立测试。
test.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<div id="show"> </div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php') // reloades data.php repetedly
}, 1000);
});
</script>
<?php echo $_SESSION["id"]; ?>
</body>
</html>
data.php
<?php
session_start();
$conn = new mysqli("localhost","id6207501_datausername","123456789","id6207501_dataname");
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT status,id FROM logs order by id desc limit 1");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$_SESSION["id"]=$row['id'];
$_SESSION["status"]=$row['status'];
}
}
?>
我希望test.php打印会话变量$_SESSION["id"]
的值,但不会。
答案 0 :(得分:1)
您必须调用AJAX get方法并设置将文本返回到data.php
文件中。
test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function () {
$.get("data.php", function(data, status){
$('#show').html(data);
});
}, 1000);
</script>
</head>
<body>
<div id="show"> <?php echo $_SESSION["id"]; ?> </div>
</body>
</html>
data.php
<?php
session_start();
// You can uncomment it and test
// $conn = new mysqli("localhost","id6207501_datausername","123456789","id6207501_dataname");
// if ($conn->connect_error) {
// die("Connection error: " . $conn->connect_error);
// }
// $result = $conn->query("SELECT status,id FROM logs order by id desc limit 1");
// if ($result->num_rows > 0) {
// while ($row = $result->fetch_assoc()) {
// echo $_SESSION["id"]=$row['id'];
// echo $_SESSION["status"]=$row['status'];
// }
// }
// Comment when you uncomment DB
// FOR example purpose
$_SESSION["id"]= rand(1,2000);
echo $_SESSION["id"];
?>
答案 1 :(得分:0)
您还可以使用本地存储。 在第一页中设置变量值。
<script>localstroage.setItem("myItem","value");</script>
然后使用getItem在另一页中获取值
<script>var x = localstroage.getItem("myItem");</script>
或者自大
<script type="text/javascript">document.cookie = "cookieName=cookieValue";</script>
在php页面中
<?php $phpVar = $_COOKIE['cookieName'];echo $phpVar ;?>
答案 2 :(得分:-2)
首先,检查会话是否在任何页面上正常工作
将此行添加到顶部
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
这既适用于使用header('Location: ')
从PHP重定向,又适用于JavaScript window.location
。