为什么我不能从 HTML 按钮调用我的 PHP 脚本


Why can I not call my PHP script from HTML button?

我正在使用HTML脚本中的按钮来取消设置cookie,但目前我无法通过该按钮单击来调用PHP脚本。

网页脚本

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WCSST 2</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type='text/css'>
</style>
</head>
<body>
<button style="color: black" <?php if(isset($_COOKIE["name"])) { ?> Disabled <?php } ?> value='Set Cookie'><b>Unset cookie</b></button>
<!-- END PAGE SOURCE -->
</body>
</html>

PHP脚本

<?php
unset($_COOKIE['name']);
unset($_COOKIE['age']);
header("Location: CM.php");
exit(0);
}
?>

如何通过单击该按钮来调用 PHP 脚本?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WCSST 2</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type='text/css'>
</style>
</head>
<body>
        <?php if(isset($_COOKIE["name"])) { ?>
        <button style="color: black" onclick="window.location.href='unset.php'"><b>Unset cookie</b></button>
        <?php }else{ ?>
        <button style="color: black" onclick="window.location.href='set.php'"><b>Set cookie</b></button>
        <?php } ?>
</body>
</html>

未设置.php脚本

<?php
unset($_COOKIE['name']);
unset($_COOKIE['age']);
header("Location: CM.php");
exit(0);
}
?>

设置.php脚本

<?php
// set your cookie
?>

你需要做的是让按钮调用一个javascript函数,该函数将调用一个Ajax,它将执行你的PHP代码。

您的 HTML 文件:

<button onclick='my_func();'>Click me</button>

你的javascript(包括jQuery,让生活更轻松(

function my_func()
{
    $.ajax({
      type: 'post',
      url: 'unset.php',
      data: {},
      dataType: 'json',
      success : function (data) {},
      error: function() {}
    });
}

您应该使用窗体来调用PHP脚本。你可以这样做:

<form action="unset.php" method="post">
<input type="submit" value="Unset cookie">
</form>

你的HTML脚本必须有.php扩展名,因为它有php脚本。

例如example.php -->包含您的 HTML 脚本。

您使用 include 语句调用以取消设置文件

<body>
    <button style="color: black" <?php 
       if(isset($_COOKIE["name"])) 
        { 
          include 'unset.php'; 
        } 
        ?> value='Set Cookie'>
   <b>Unset cookie</b></button>
<!-- END PAGE SOURCE -->
</body>

或者您可以使用JAVASCRIPT点击功能

是的,首先你不能将php脚本代码写入.html文件中,因此为此创建.php文件,并在该文件中写入整个代码。 还有一件事是对于未设置的cookie,您必须使用正常表单方法发送POST请求,或者您也可以使用Ajax调用例如

<form name="abc" id="abc" method="post">
<input type="submit" name="unset" value="Unset Cookies">
</form>
<?php
if($_POST)
{
unset($_COOKIE['name']);
unset($_COOKIE['age']);
header("Location: CM.php");
exit(0);
}
?>