正如 Thorben 提到的,您无法在浏览器事件上执行 PHP 函数,因为该语言是服务器端而不是客户端。然而,有几种方法可以解决这个问题:
1. 服务器端(PHP)
您不能在浏览器事件(例如链接单击)上调用 PHP 函数,但您可以can当您单击超链接时,在加载的页面上首先将其称为“next.php”。为此,请调用您的函数deleteUserMeta()
有条件地位于“next.php”的最顶部。问题是您需要将一些变量传递到此页面,以便您可以检查条件并执行该函数。使用 GET 通过超链接传递变量,如下所示:
<a href="next.php?unsubscribe=true&userID=343">Unsubscribe</a>
如何传递 userId 由您决定。在上面的示例中,它是硬编码的,但您也可以使用 PHP 来设置它,如下所示:
<a href="next.php?unsubscribe=true&userID=<?php echo $userID;?>">Unsubscribe</a>
现在在“next.php”上,使用条件来评估该变量:
<?php
if($_REQUEST['unsubscribe'] == 'true'){
deleteUserMeta($_REQUEST['userID']);
}
?>
2. 客户端(AJAX)
执行此操作的另一种方法是使用 AJAX 在客户端执行此操作。如果您不熟悉 Javascript/jQuery/AJAX,我可能会坚持使用其他解决方案,因为它可能更容易实现。如果您已经在使用 jQuery,那么这应该不会太难。使用 jQuery,您可以将此函数绑定到超链接的实际单击事件。这样,整个操作就可以在不刷新页面的情况下进行:
<a href="#" onclick="ajaxDeleteUserMeta()">Unsubscribe/a>
现在你需要两件事:
1. 第一个解决方案所需的相同 PHP 文件“next.php”仅包含对您的函数的调用,deleteUserMeta($userId)
2. 一个名为的 JavaScript 函数ajaxDeleteUserMeta()
,所以在你的 JS 中创建一个这样的:(因为这是一个命名函数,所以不需要进入内部jQuery(document).ready(function(){});
就像大多数匿名 jQuery 函数一样。)
function ajaxDeleteUserMeta(){
var userID = ''; // fill this in to somehow acquire the userID client-side...
jQuery.ajax({
type: "POST",
url: "next.php", /* this will make an ajax request to next.php, which contains the call to your original delete function. Essentially, this ajax call will hit your original server-side function from the client-side.*/
data: "userID="+userID+"&unsubscribe=true", /*here you can pass a POST variable to next.php that will be interpreted by the conditional function.*/
success: function(msg){
alert( "Data Saved: User ID " + userID + " deleted." );
}
});
}
啰嗦了,但我希望其中有些道理。