繁体   English   中英

从jQuery调用REST API服务

[英]call rest api service from jquery

我试图理解宁静的服务。我可以创建一个类并在其中定义一个函数,但是当我通过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);
}

您应该将数据类型发送到服务器。

试试这个代码:

$.post( "db/api/demo")
      .done(function( data ) { 
        $.each(data, function(index, element) {
            alert('Data: ' + element.data + ' Status: ' + element.status);   
        });
      }, "json"); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM