【问题标题】:Ajax call method from class php来自类 php 的 Ajax 调用方法
【发布时间】:2012-05-27 03:27:27
【问题描述】:

你好,

我想通过 ajax 从一个类中调用一个方法。 这个类是这样的:

class MyClass{
      public function myMethod($someParameter,$someParameter2){
          //do something
          return $something;
      }
      private function myMethod2($someParameter3){
          //do something
          return something;
      }

}

我可以使用 ajax 调用一个类方法 (myMetod(2,3)) 并返回做一些事情吗? 可以这样用吗?

$.ajax({
        url : 'myClass.php',
        data : {
                    someData: '2,3',
               }
        type : 'POST' ,
        success : function(output){
                  alert(output)
        }
});

【问题讨论】:

    标签: php ajax class methods


    【解决方案1】:

    我可以使用ajax 来调用类方法 (myMetod(2,3)) 并使用 回来做点什么?

    是的,你可以。

    由于调用类方法需要初始化 myClass.php 中的对象,因此您需要实例化类并传递正确的输入,如果类方法要返回一些输出,只需回显即可。

    例如。如果您想拨打 myMethod,请从您的 ajax 呼叫中拨打您的 myClass.php

    //Check for ajax request to instantiate the class.
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
       $object = new MyClass();
       //hold the return value in a variable to send output back to ajax request or just echo this method.
       $result = $object->myMethod($_POST['value'], $_POST['value2']);
       echo $result;
    }
    

    【讨论】:

      【解决方案2】:

      你需要创建一个调用这个类方法的php脚本,并且可以作为ajax请求调用。创建一个文件,如:

      例如:

      myfile.php

      <?php
      
         $date = $_POST; // print_r( $_POST ); to check the data
      
         $obj = new MyClass();
      
         $obj->myMethod( $_POST['field1'], $_POST['field2'] );
         $obj->myMethod2( $_POST['field1'] );
      
      ?>
      

      并将您的 jQuery 代码更改为:

      $.ajax({
              url  : 'path/to/myfile.php',
              data : { someData: '2,3' },
              type : 'POST' ,
              success : function( output ) {
                          alert(output)
                        }
      });
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      相关资源
      最近更新 更多