AJAX request and PHP class functions

后端 未结 8 863
小鲜肉
小鲜肉 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:57

    You need one additional script, because your animal class can't do anything on its own.

    First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.

    Use this new script as the target of your Ajax request instead of targeting animal.php.

    0 讨论(0)
  • 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

    <?php
    
    // Include the class you want to call a method from
    
    echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->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 ^^

    0 讨论(0)
提交回复
热议问题