php 如何在html按钮上执行php函数点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31193042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:18:05  来源:igfitidea点击:

how to execute php function on html button click

phphtml

提问by Bisher Andoura

Hello I want to execute bb()function on button click.
I tried following code but it did not work.

您好,我想bb()在单击按钮时执行功能。
我尝试了以下代码,但没有用。

echo "<div class ='i2' id=".$x.">";
echo "<button type='button' style='display: none;' id='i' name='delete' onclick='document.body.removeChild(this.parentNode)'>";
echo"</button>";
echo "</div>";

<?php

function bb()
{
 echo "hello";
}
if (isset($_GET['delete'])) {
 bb();
}

?>

回答by Jose Manuel Abarca Rodríguez

Your button is HTML and your function is PHP. They look like together because they are in the same file, but they are not together. PHP exists only on the server. HTML only works on the client (browser). When you see the button on your browser, the PHP is gone, you only have HTML.

您的按钮是 HTML,您的功能是 PHP。它们看起来像在一起,因为它们在同一个文件中,但它们并不在一起。PHP 只存在于服务器上。HTML 仅适用于客户端(浏览器)。当您在浏览器上看到按钮时,PHP 消失了,您只有 HTML。

To make a HTML button to call a PHP function, you will have to move your function to a PHP file, then make your button to call it with Ajax. Example:

要制作一个 HTML 按钮来调用 PHP 函数,您必须将您的函数移动到一个 PHP 文件中,然后制作您的按钮以使用 Ajax 调用它。例子:

bb1.html: contains button that uses Ajax to call PHP function.

bb1.html: 包含使用 Ajax 调用 PHP 函数的按钮。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
          data : { },
          url  : 'bb2.php',              // <=== CALL THE PHP FUNCTION HERE.
          success: function ( data ) {
            alert( data );               // <=== VALUE RETURNED FROM FUNCTION.
          },
          error: function ( xhr ) {
            alert( "error" );
          }
        });
}
    </script>
  </head>
  <body>
    <button onclick="myAjax()">Click here</button> <!-- BUTTON CALL PHP FUNCTION -->
  </body>
</html>

bb2.php: contains function that returns "hello".

bb2.php:包含返回“hello”的函数。

<?php

function bb()
{
echo "hello";  // VALUE RETURNED.
}

bb();

?>

Create two text files with the given names, copy-paste this codes, open your browser and run "localhost/bb1.html".

创建两个具有给定名称的文本文件,复制粘贴此代码,打开浏览器并运行“localhost/bb1.html”。

This is how a button calls a PHP function : Ajax does all the magic.

这就是按钮调用 PHP 函数的方式:Ajax 发挥了所有作用。