【问题标题】:CodeIgniter Restserver doesn't work with specific URL'sCodeIgniter Restserver 不适用于特定的 URL
【发布时间】:2013-01-30 15:43:31
【问题描述】:

我将这个Restserver 与 CodeIgniter 结合使用。

它似乎工作得很好,除非我使用这样的 URL; mydomain.com/api/example/1234/

其中 1234 是我请求的 ID。

这样的代码似乎不起作用:

class Example extends REST_Controller {
    public function index_get() {
        print($this->get("example"));
    }
}

无论是 GET 还是 POST 请求似乎都无关紧要。一定有一种方法可以让我从 URL 中检索 ID..

【问题讨论】:

  • $this->get('id')index_get() 中的回声是什么?
  • 什么都没有,因为 index_get() 根本没有被调用:{"status":false,"error":"Unknown method."}
  • 您可以尝试将您的方法重命名为 example_get() 而不是 index_get() 吗?
  • 听起来合乎逻辑,但如果我这样做,主 URL 甚至不再起作用(没有附加 ID 的 URl,例如 mydomain.com/api/example)

标签: php codeigniter rest


【解决方案1】:

URL 的段应该等于这些:

api = Controller
example = Resource

参数必须是键值对:

id = Key
1234 = Value

您的 1234 似乎被当作钥匙,但没有任何价值。尝试将您的 URL 更改为以下内容:mydomain.com/api/example/id/1234/,这将转换为:mydomain.com/controller/resource/key/value/

这里也有很详细的教程:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

编辑: 由于您的控制器位于子文件夹中,因此您的 URL 段应该这样构造:

api/example = Controller
user = Resource // basically the method name + the http method e.g. user_get(), or user_post(). I just made 'user' up, for your app can be whatever it is that people will access via your api

参数必须以键值对的形式提供:

id = Key
1234 = Value

那么您的网址将如下所示:mydomain.com/api/example/user/id/1234/

【讨论】:

  • 是的,我知道这一点。我只是无法真正更改请求 URL,因为我不是对发出的请求进行编码的人;)需要坚持一些巧妙的路由。
【解决方案2】:

在 GET REQUEST 的情况下,您只需在函数头中定义参数,如下所示:

public function index_get($param) {
    print($param);
}

如果你想让它成为可选的,那么:

public function index_get($param="") {
    if ($param=="") {
       print("No Parameters!");
    } else {
       print($param);
    }
}

如果我想发送“POST”参数,我只需创建一个 POST METHOD 并接收它们......

public function index_post() {
$params = $this->post();
if (isset($param['id'])) {
   print($param['id']);
} else {
   print("No Parameters!");
}

}

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2016-05-21
    • 2016-08-18
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多