gpt4 book ai didi

javascript - 如何访问另一个网页中的一个php变量

转载 作者:行者123 更新时间:2023-12-01 01:53:27 25 4
gpt4 key购买 nike

访问另一个网页中的 session 变量时遇到一些问题

我尝试使用jquery刷新创建 session (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 变量 $_SESSION["id"] 的值,但事实并非如此。

最佳答案

您必须调用 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"];

?>

关于javascript - 如何访问另一个网页中的一个php变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55449070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com