我是Jquery和Ajax的新手。请忍受我愚蠢的问题。
我正在尝试通过 ajax 调用在类内调用方法说 test(( hello。
你好.php
class hello
{
public function test()
{
//some data
}
public function abc()
{
//some data
}
}
现在我想从另一个 PHP 文件调用 test(( ...
例如:
乙.php
$.ajax({
url : 'hello.php->test()', //just for example i have written it bcz it should call only test() not abc()..
})
可以直接调用它吗? 我已经浏览了 $.ajax(( API,但我没有发现任何有用的东西。
所有的答案将不胜感激...
试试这个:
你好.php
class hello
{
public function test()
{
//some data
}
public function abc()
{
//some data
}
}
if(isset($_GET['method'])){
$hello = new hello;
$hello->$_GET['method']();
}
乙.php
$.ajax({
url : 'hello.php?method=test', //just for example i have written it bcz it should call only test() not abc()..
})
顺便说一下,通过 ajax 请求公开您的类并不安全。
一种方法是通过 ajax POST 或 GET 传递类的名称、构造函数参数以及方法名称和参数等,例如:
var url = 'callMethod.php';
var data = {
str_className: 'Hello',
arr_consArgs: {arg1: 'test1'},
str_methodName: 'test'
};
$.post(url, data, function(response) {
etc.
});
在名为 callMethod.php
的 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;
}
哪里:
function fuNew($classNameOrObj, $arr_constructionParams = array()) {
$class = new ReflectionClass($classNameOrObj);
if (empty($arr_constructionParams))
return $class->newInstance();
return $class->newInstanceArgs($arr_constructionParams);
}