AJAX request and PHP class functions

后端 未结 8 886
小鲜肉
小鲜肉 2020-12-08 05:29

How to call a PHP class function from an ajax call

animal.php file

class animal
{     
  function getName()
  {
    return \"lion\";
  }         


        
8条回答
  •  渐次进展
    2020-12-08 05:58

    I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:

    ajax_handler.php

    invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
    

    some.js

    function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
        $.ajax({
            type: 'POST',
            url: 'ajax_handler.php',
            data: {
                className: className,
                methodName: methodName,
                parameters: parameters
            },
            success: successCallback,
            error: xhr => console.error(xhr.responseText)
        });
    }
    

    Greetings ^^

提交回复
热议问题