点击"取消"按钮后,我想销毁$_SESSION['userList']。但是,在页面加载时,$_SESSION['userList']会被销毁。
以下是我的代码:
<a href='#' class="btn" onClick="resetForm()"><span>Cancel</span></a>
<script type="text/javascript">
function resetForm() {
<?php
unset($_SESSION['userList']);
?>
}
</script>
非常感谢您的帮助。
您不能在javascript(客户端)中执行PHP(服务器端)。您需要发出一个HTTP请求来调用PHP。您可以使用AJAX来实现这一点。
JAVASCRIPT
$.ajax({
type: "POST",
url: "phppage.php",
data: "action=unsetsession",
success: function(msg){
alert(msg);
if(msg == "success"){
//cleared session
}else{
//failed
}
},
error: function(msg){
alert('Error: cannot load page.');
}
});
PHP
if($_POST['action'] == "unsetsession"){
unset($_SESSION['userList']);
echo "success";
}
您不能像在示例中那样在客户端执行php代码。如果您想在重新加载时销毁会话,则必须使用ajax请求。
您最好将jquery用于此
<a href='#' class="btn" onClick="resetForm()"><span>Cancel</span></a>
<script>
function resetForm()
{
jQuery.ajax({
type: "POST",
url: "cancel.php",
data:,
cache: false,
success: function(response)
{
}
});
}
</script>
并创建一个新的cancel.php
,它将是这样的-
<?php
unset($_SESSION['userList']);
?>
你不能像这样从JS调用PHP。您需要回拨服务器。
使用提交按钮取消(您可以使用CSS使其看起来像您想要的那样)//HTML
<form method="post" >
<input type="button" value="Cancel" name="cancel" id="cancel" />
</form>
//PHP
if(isset($_POST['cancel'))
{
unset($_SESSION['userList']);
}