如何用一个参数在点击按钮时调用php函数


How to call a php function on button click with one param

当我按下按钮时,我想调用一个带有一个参数(按钮id)的php函数。这就是我尝试的:

<!DOCTYPE html>
<html>
<body>
<?php
include ("sterge2.html");
<button onclick="writeMsg(this.id)">Click me</button>
function writeMsg($id) {
     echo $id."Hello world!";
     //add that id in a database...
}

?>
</body>
</html>

但它什么都没做。。。

您不能将javascript和php组合在一起。而不是使用ajax。请尝试以下ajax代码。。

 <button class="btnsubmit" id="submit" data-id="5" >Click me</button>
    $(".btnsubmit").click(function() {
                   var id = $(this).attr('data-id');
                       $.ajax({
                       url : URL+'writeMsg',
                       type : 'POST',
                       data : {'id': id},
                       success : function(data)
                       {
                       }
                   });
                });

并在writeMsg函数中执行数据库操作。我希望这个代码能对你有所帮助。

试试这个:

<!DOCTYPE html>
<html>
    <body>
        <?php
        include ("sterge2.html");
        echo '<button onclick="writeMsg(this.id)">Click me</button>';
        ?>
        <script>
        function writeMsg(id) {
             alert(id + "Hello world!");
             // Use AJAX to call PHP file and save id into DB
        }
        </script>
    </body>
</html>

使用onclick-事件,您可以调用javascript函数。不是php。试试这个。

<!--html -->
<button  onclick="writeMsg(<?php echo $id_val ?>)">Click me</button>
<!--html -->

函数将包含在javascript 中

<script type="text/javascript>">
var id;
function writeMsg(id) {
      alert(id."Hello world!");//give you result
}
</script>