【发布时间】:2014-06-02 12:49:42
【问题描述】:
我正在尝试了解restful services。我可以创建一个类并在其中定义一个函数,但是当我通过jquery调用它时它返回null,当我通过在地址栏中键入url直接调用时它返回一个json响应
这是代码
class Api extends REST
{
public function processApi()
{
$func = strtolower(trim(str_replace("api/","",$_REQUEST['request'])));
if((int)method_exists($this,$func) > 0)
{
$this->$func();
}
else
{
$this->response('',404); // If the method not exist with in this class, response would be "Page not found".
}
}
private function json($data)
{
if(is_array($data))
{
return json_encode($data);
}
}
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
$this->response($this->json($error), 200);
}
}
$api = new Api;
$api->processApi();
我只想从 jquery 调用演示方法。这就是我正在尝试的
$.post("db/api/demo",
function(data,status){
data = jQuery.parseJSON(data);
alert("Data: " + data + "\nStatus: " + status);
});
当演示方法是这样时,我通过 jquery 得到响应
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
echo json_encode($error);
//$this->response(json_encode($error), 200);
}
【问题讨论】:
-
试试
$this->response($this->json_encode($error), 200); -
并调试它,在浏览器上 f12 看看哪个 url 被击中,也尝试绝对 url 然后测试
-
Holybreath 这不起作用。我在类外创建 Api 对象并现在从 jquery 调用可以吗
-
你能告诉我为什么这条线不起作用
$this->response(json_encode($error), 200);