Call php function from JavaScript

后端 未结 4 615
一个人的身影
一个人的身影 2020-11-21 06:38

Is there a way I can run a php function through a JS function?

something like this:



        
4条回答
  •  春和景丽
    2020-11-21 06:53

    The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:

    function someFunction() {
        echo 'Answer';
    }
    
    if ($_GET['do'] === "someFunction") {
        someFunction();
    }
    

    and then, catch the answer with JS (i'm using jQuery for making AJAX requests)

    Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.

提交回复
热议问题