如何实现onclick for php按钮


how to implement onclick for php button

我在php代码中有一行内容如下:

echo '<div class="sample-button"><a href="#">Do something</a></div>'

这将在页面上显示一个可单击的文本链接。现在我想点击这个链接应该调用一个php函数myFunc(),我在同一个php文件中定义了这个函数。我该如何实现?

<a href="#">的目标是什么都是你的答案。路径需要是<a href="#?call=1">

现在设置好了,您需要创建一个if语句
if ($_GET['call'] === 1){ myFunc(); }

当您单击该链接时,它应该刷新页面,url现在设置为:localhost/page.php?call=1。当php页面刷新时,它可以调用MyFunc()。

您可以在单击时调用JS函数,而不是php函数。我认为您必须更好地查看有关php语言用途的文档。

如果你真的想通过点击链接来执行php脚本,你可以使用jquery ajax。

在您的情况下,通过监听按钮的点击事件来调用函数所在的同一php文件,并执行ajax请求:

$('.sample-button').click(function() {
  // Ajax Call
  $.ajax({
    url: "/path_to_your_script.php",
    contentType: "application/x-www-form-urlencoded",
    type: "POST",
    data: {callFunction:true},
    success: function(response){
        // Check your response
    },
    error: function(){
       // Error handling
    }
   });
});

在php脚本的顶部,您需要检查:

<?php
if (!empty($_POST['callFunction'])) {
   your_function() {

       return $yourResponse;
   }
    exit();
}

一个快速示例(未经测试),展示了如何在单击页面上的标准链接后调用php函数并使用响应。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) && $_POST['action']=='call_my_func' ){
        /* ensure we discard the buffer if we need to send a response */
        ob_clean();
        function myFunc($var){
            echo 'PHP function...';
        }
        /* call your function */
        call_user_func( 'myFunc', 'some variable' );
        exit();
    }
?>

<script type='text/javascript'>
        function invoke_myfunc(){
            var http=new XMLHttpRequest();
            http.onreadystatechange=function(){
                if( http.readyState==4 && http.status==200 ) alert( http.response );
            };
            var headers={
                'Content-type': 'application/x-www-form-urlencoded'
            };
            http.open('POST', document.location.href, true );
            for( header in headers ) http.setRequestHeader( header, headers[ header ] );
            http.send( [ 'action=call_my_func' ].join('&') );
        }   
</script>
<?php
    /*
       in your page
       -------------
    */
    echo '<div class="sample-button"><a href="#" onclick="invoke_myfunc()">Do something</a></div>';
?>