2010-12-06 70 views

回答

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) { 
}); 
+0

好的答案。如果將來我需要類似的東西 – 2010-12-06 02:10:36

2

在PHP腳本中,每個函數都包含一個if語句,用於檢查GET變量。然後在JS中發送一個特定於調用該函數所需的GET變量。

0

ajax也是一個http請求,它不能直接調用php函數