通过AJAX访问PHP类函数 [英] Accessing a PHP class function through AJAX

查看:98
本文介绍了通过AJAX访问PHP类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我如何通过AJAX(使用jQuery)从PHP类直接访问函数.

Does anyone know how I can directly access a function from a PHP class through AJAX (using jQuery).

PHP:

class Blah
{
    function __construct()
    {
    }

    function doSomething(data)
    {
        echo "I am not an animal";
    }
}

jQuery:

$.ajax({
        url: myClass.php,
        data: Blah.doSomething(); "or" Blah->doSomething()  "or whatever"
    });

我知道这是一个粗糙的示例,我只是想说明一个观点,希望您能理解我的问题的要点.

I know this is a crude example, i'm just trying to illustrate a point, I hope you can get the gist of my question.

此刻,我正在按照以下方式进行操作:

At the moment i'm doing something along these lines:

$.ajax({
        url: myClass.php,
        data: data : { 'type':'doSomething' }
    });

||

if(POST['data']['type'] == 'doSomething')
{
     $this->doSomething();
}

我不喜欢它...

推荐答案

您需要创建该类的对象,然后调用所需的方法. 类声明不执行任何代码.

You need to create an object of that class and then invoke the methods you need. The class declaration doesn't not execute any code.

例如,您可以将其添加到类的下方:

For example, you can add this below the class:

class Blah { ... }
$b = new Blah();
$b->doSomething();

更新:

如果要调用POST中发送的方法,则可以使用函数call_user_function:

If you want to invoke the method sent in POST, you can use the function call_user_function:

$method_name = $_POST['method'];
$b->{$method_name}();

查看更多详细信息: http://php.net/manual/en/function.call-user-func.php

这篇关于通过AJAX访问PHP类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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