JavaScript可以直接调用PHP函数,或是否需要单独的PHP文件来调用该函数? [英] Can JavaScript call a PHP function directly, or do I need separate php file to call the function?

查看:110
本文介绍了JavaScript可以直接调用PHP函数,或是否需要单独的PHP文件来调用该函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一些基本的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) {
});

这篇关于JavaScript可以直接调用PHP函数,或是否需要单独的PHP文件来调用该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆