如何实现onclick for php按钮

时间:2015-11-16 13:40:11

标签: php html

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

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

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

4 个答案:

答案 0 :(得分:1)

无论你的答案是<a href="#"> gos。 路径必须为<a href="#?call=1">

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

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

答案 1 :(得分:0)

你可以在点击时调用JS函数,而不是php函数。我认为你必须更好地检查文档,了解php语言的目的是什么。

答案 2 :(得分:0)

一个快速示例(未经测试),展示如何调用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>';
?>

答案 3 :(得分:0)

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

在你的情况下,通过听按钮的click事件调用函数所在的同一个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();
}