2

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

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

4

3 回答 3

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

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

$.get("/functions.php?f=func_name_to_call", {name: "John", hobby: "Programming"}, function(data) {
});
于 2010-12-06T02:08:34.343 回答
2

在 PHP 脚本中,用 if 语句围绕每个函数来检查 GET 变量。然后在 JS 中发送一个 GET 变量,该变量特定于调用该函数所需的变量。

于 2010-12-06T02:09:02.660 回答
0

ajax也是http请求,不能直接调用php函数

于 2010-12-06T02:40:10.933 回答