最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

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

Share Improve this question edited Dec 6, 2010 at 2:12 Moshe 58.1k80 gold badges277 silver badges430 bronze badges asked Dec 6, 2010 at 2:01 DamonDamon 10.8k17 gold badges91 silver badges146 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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

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.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论