繁体   English   中英

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

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

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

HTML脚本

<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脚本必须具有.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 onclick函数

您需要做的是使按钮调用javascript函数,该函数将调用Ajax,该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 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>

unset.php脚本

<?php

unset($_COOKIE['name']);
unset($_COOKIE['age']);

header("Location: CM.php");
exit(0);
}
?>

set.php脚本

<?php
// set your cookie
?>

是的,首先您不能将php脚本代码编写到.html文件中,因此要创建.php文件,并在整个代码上方写上该代码。 还有一件事是未设置的cookie,您必须使用通常的表单方法发送发布请求,或者您也可以使用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); } ?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM