duanrebo3559 2013-09-27 10:53
浏览 105

如何使用jquery Ajax调用调用类的方法

i am newbie in Jquery and Ajax.. Please bear with my stupid problem..

i am trying to call method say test() inside class hello through ajax call..

hello.php

class hello
{
      public function test()
      {
        //some data
      }

      public function abc()
      {
        //some data
      }
}

now i want to call test() from another php file...

for example:

b.php

  $.ajax({
    url : 'hello.php->test()', //just for example i have written it bcz it should call only test() not abc()..
   })

is it possible to call it directly? i have went through $.ajax() api but i din't found anything helpful..

All answer will be appreciates...

  • 写回答

2条回答 默认 最新

  • ds211107 2013-09-27 11:21
    关注

    One approach is to pass the name of the class, the constructor arguments, and the method name and arguments etc. via ajax POST or GET, for example:

    var url = 'callMethod.php';
    var data = {
        str_className: 'Hello',
        arr_consArgs: {arg1: 'test1'},
        str_methodName: 'test'
    };
    $.post(url, data, function(response) {
        etc.
    });
    

    In PHP script named callMethod.php:

    /* Place your 'Hello' class here */
    
    // class
    $str_className = !empty($_POST["str_className"]) ? $_POST["str_className"] : NULL;
    if ($str_className) {
        // constructor
        $arr_consArgs = !empty($_POST["arr_consArgs"]) ? $_POST["arr_consArgs"] : array();
    
        // method
        $str_methodName = !empty($_POST["str_methodName"]) ? $_POST["str_methodName"] : NULL;
        if (!empty($str_methodName)) {
            $arr_methodArgs = !empty($_POST["arr_methodArgs"]) ? $_POST["arr_methodArgs"] : array();
        }
    
        // call constructor
        $obj = fuNew($str_className, $arr_consArgs);
    
        // call method
        $output = NULL;
        if (!empty($str_methodName)) 
            $output .= call_user_func_array(array($obj, $str_methodName), $arr_methodArgs);
    
        // echo output
        echo $output;
    
    }
    

    where:

    function fuNew($classNameOrObj, $arr_constructionParams = array()) {
        $class = new ReflectionClass($classNameOrObj);
        if (empty($arr_constructionParams))
            return $class->newInstance();
        return $class->newInstanceArgs($arr_constructionParams);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器