我想做的是使用变量从一个使用 php 的页面传递一个值到另一个使用 php 的页面,然后在第二页中将该值从 php 传递到 javascript。
我根据我点击的图像来初始化 HTML 中的变量。 问题是,每次我传递不同的值(下面的代码中不同的值是 12 和 7),这意味着我点击了不同的图像,并且在重新加载页面后,我仍然得到第一个值。
我尝试取消设置变量和/或 session_destroy() 但没有成功。更清楚地说:
首页:
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="secondpage.php"><img src="images/first_image.png" alt="image" <?php $_SESSION['choice'] = 12; ?>></a>
<a href="secondpage.php"><img src="images/second_image.png" alt="image" <?php $_SESSION['choice'] = 7; ?>></a>
</body>
</html>
第二页:
<?php
session_start();
$option = $_SESSION['choice'];
//unset($_SESSION['choice']); //failed
echo $option; //option is always 12
//session_destroy(); //failed
?>
<!doctype html>
<html>
<head>
<title>Monuments</title>
<script>
var option = <?php echo json_encode($option); ?>;
//var option = "<?php echo $option; ?>"; // i tried also this way
alert("option is : " + option); //option is always 12
</script>
</head>
<body>
</body>
</html>
你能告诉我问题是什么吗? 或者针对我想做的事情推荐任何更好的解决方案?
最佳答案
您正在为 HTML
中的 $_SESSION['choice']
赋值。
使用 session
并不是真正实现您想要实现的目标的正确方法。
在您的首页上,使用 $_GET
参数来标识所选纪念碑。
<a href="secondpage.php?choice=12"><img src="images/first_image.png" alt="image"></a>
在第二页上,您可以使用 $_GET['choice']
获取此参数
更改后的代码:
<!DOCTYPE HTML>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="secondpage.php?choice=12"><img src="images/first_image.png" alt="image"></a>
<a href="secondpage.php?choice=7"><img src="images/second_image.png" alt="image"></a>
</body>
</html>
第二页:
<?php
$option = $_GET['choice'];
echo $option;
?>
<html>
<head>
<title>Monuments</title>
<script>
var option = <?php echo $option; ?>;
alert("option is: " + option);
</script>
</head>
<body>
</body>
</html>
关于javascript - 从页面传递到另一个页面的变量值保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22723892/