2012-05-20 67 views
10

嗨,来自php类的Ajax调用方法

我想通过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) 
     } 
}); 

回答

7

您需要创建的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) 
        } 
}); 
+0

感谢you.It工作如果 – Razvan

+0

我想要调用具体的ajax调用的具体方法吗?可能吗 ? – Sadanand

+0

@Sadanand请参考答案http://stackoverflow.com/questions/17489109/ajax-request-and-php-class-functions –

3

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

是的,你可以。

由于调用类方法需要在您的myClass.php中对象的初始化,您需要实例化类并传递正确的输入,并且如果类方法返回某个输出,则只需对其进行回显。例如

。从你的Ajax调用,如果你想然后调用myMethodmyClass.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; 
}