JavaScript可以直接调用PHP函数,或是否需要单独的PHP文件来调用该函数?函数、直接调用、文件、JavaScript

2023-09-10 17:59:31 作者:乖乖到我怀里来

我在做一些基本的Ajax的东西(不是jQuery的..刚学的基础知识),我有一个大致的结构设置,其中HTML调用JavaScript函数,将数据发送到并运行特定的PHP页面。

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.

但是,如果我只需要运行这已经在functions.php中定义的PHP函数。这是可能的呢?我累了做新的php文件,每个任务的;)

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 ;)

推荐答案

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

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']);
}

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

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

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