Run a PHP function upon button click?

前端 未结 8 1662
小鲜肉
小鲜肉 2021-01-03 04:24

I want to run a PHP function with an HTML button click.

I can call a PHP script this way:

Name
8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 04:29

    The method I prefer to use is a mixture of jQuery/ajax calling an Object Oriented PHP class.

    I have a jQuery listener/trigger for the button press with something like this:

    $('#buttonId').live('click', function() {
        $.get('api.php?functionName=test&inputvar=something');
    
        return false;
    });
    

    That will call the api.php file through ajax and prevent any further action, such as form submission.

    Then in the PHP file you could always do something basic like:

    if ($_REQUEST['functionName'] == 'test') {
        test();
    }
    

    or if you have huge classes and alot of dynamic input you could do something more interesting like:

    $functionName = $_REQUEST['functionName'];
    if (method_exists($myClassInstance, $functionName))
        $myClassInstance->$functionName();
    

    There are numerous ways to approach this, but these are my favorites. Another alternative is the Extjs framework which is built for this kind of activity but if you are not familiar with it already and the project is not 'huge' I would not concern myself with it.

    Lastly, if you are needing to get a response back from the php file such as json results, then instead of using the jQuery: $.get() function, use the function $.getJSON

    Hope that helps :)

提交回复
热议问题