【问题标题】:call rest api service from jquery从 jquery 调用 rest api 服务
【发布时间】: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);

标签: php jquery json rest


【解决方案1】:

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

试试这个代码:

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

【讨论】:

  • 你能告诉我如何使用 jQuery $.ajax 方法调用相同的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 2016-08-26
  • 2010-12-12
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多