JavaScript可以直接调用PHP函数,还是需要单独的php文件来调用函数?

Dam*_*mon 2 javascript php ajax function-calls

我正在做一些基本的Ajax的东西(不是jquery ...只是学习基础知识),我有一个通用的结构设置,其中html调用一个javascript函数,它发送数据并运行一个特定的PHP页面.

但是,如果我只需要运行已在functions.php中定义的php函数,该怎么办?这有可能吗?我厌倦了为每个任务制作新的php文件;)

And*_*ong 10

你可以在php中定义一个类来处理这样的东西,例如:

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']);
}
Run Code Online (Sandbox Code Playgroud)

然后像你这样做你的ajax调用(假设jQuery):

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