Can JavaScript call a PHP function directly, or do I need separate php file to call the function?

穿精又带淫゛_ 提交于 2019-12-12 10:00:54

问题


I am doing some basic Ajax stuff (not jquery.. just learning the basics), and I have a general structure set up where html calls a javascript function which sends data to and runs a specific php page.

But what if I just need to run a php function that's already defined in functions.php. Is that possible at all? I'm getting tired of making new php files for every task ;)


回答1:


You could define a class in php to handle stuff like this, such as:

functions.php:

class MyFunctions {
   function foo() {
      // code here
      // if you need to pass in some parameters, you can do it via jQuery and fetch the data like so (for the jQuery, see below)
      if($_GET['name'] == "john") { } // do stuff
   }

   function bar() {
      // code here
   }

   static function handleFn($fName) {
      if(method_exists(__CLASS__, $fname)) {
         echo $this->{$fname}(); die; // since AJAX, just echo the output and stop executing
      }
   }
}

if(!empty($_GET['f'])) {
   MyFunctions::handleFn($_GET['f']);
}

Then do your ajax call like so (assuming jQuery):

$.get("/functions.php?f=func_name_to_call", {name: "John", hobby: "Programming"}, function(data) {
});



回答2:


In the PHP script surround each function with a if statement designed to check a GET variable. Then in the JS send a GET variable specific to the one required to call that function.




回答3:


ajax is also an http request, which cannot call php functions directly



来源:https://stackoverflow.com/questions/4362589/can-javascript-call-a-php-function-directly-or-do-i-need-separate-php-file-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!