我有一个页面,您可以在其中查看购物车中的内容(显然正在进行中),并且有一个按钮可以清除购物车,它可以工作,但是移动到站点中的另一个页面,无论是通过单击链接还是在地址栏中键入,都会运行表单操作。它还会在产品页面上执行此操作以添加到购物车中。如何阻止这种情况的发生,以便仅在按下按钮时运行操作?
<div id="">
<?php echo "You have " . $_SESSION['cartItems'];
if($_SESSION['cartItems'] == 1){
echo " item";
} else {
echo " items";
}
echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
<form action="<?php session_destroy();?>"><input type="submit" value="Clear Cart"></form>
</div>
过了一段时间,我明白了你想做什么。您不能销毁会话的操作属性,但可以将会话销毁的页面归于操作属性
破坏.php
<?php
session_start();
session_destroy();
echo 'destroyed';
?>
您的主文件
<div>
<?php
echo "You have " . $_SESSION['cartItems'].($_SESSION['cartItems'] > 1 ? 'items' : 'item');
echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
<form action="destroy.php"><input type="submit" value="Clear Cart"></form>
</div>
你也可以把 =" 放进去,使用一些隐藏的参数,检查它是否应该被销毁,例如:
一个文件解决方案:
<div>
<?php
session_start();
if(isset($_POST['destroy']) && $_POST['destroy'] == 1) session_destroy(); //destroying session
echo "You have " . $_SESSION['cartItems'].($_SESSION['cartItems'] > 1 ? 'items' : 'item');
echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
<form method="POST" action="">
<input type="submit" value="Clear Cart"><input type="hidden" value="1" name="destroy">
</form>
</div>
这个:
<form action="<?php session_destroy();?>">
可能没有做你认为它正在做的事情。
session_destroy()
不是表单执行的操作。 无论表单如何,在加载页面时,无论表单如何,都会在加载页面时执行。 您正在以一种没有真正意义的方式混合服务器端和客户端代码。
呈现页面时,将在服务器上解释服务器端代码。 所有这一切。 该代码的结果将呈现到页面。 因此,这里发生的事情是,每次加载页面时,您都在运行session_destroy()
,然后将session_destroy()
的输出用作表单操作。
输出是一个布尔值,因此您的表单标签可能最终如下所示:
<form action="true">
这并没有真正做任何有意义的事情。
如果要销毁表单提交上的会话,则提交操作需要针对销毁会话的页面。 像这样在页面本身上调用session_destroy()
将导致在加载页面时始终调用session_destroy()
。 不是在您离开时,而是在页面加载时。