使用JSON输入的CakePHP API PUT


CakePHP API PUT with JSON input

我正在使用CakePHP构建一个API。

我想从我的移动应用程序使用PUT来更新数据。格式是JSON作为输入,但$this->data似乎为空。

我从我的应用程序调用这个url(在文档中指定):123./菜谱/json

在我的"食谱"(或其他)我有以下控制器:

function edit($id = null) {
    $this->User->id = $id;
    if (empty($this->data)) {
        $this->data = $this->User->read();
        $message = array('StatusCode' => 999, 'ERROR' => "");
    } else {
        if ($this->User->save($this->data)) {
            $message = array('StatusCode' => 200, 'ErrorCode' => "");
        } else {
            $message = array('StatusCode' => 400, 'ErrorCode' => "UnknownError");
        }
    }
    $this->set(compact("message"));
    $this->set('albums', $this->User->Album->find('list'));
}

我在我的应用程序中正确地接收到JSON响应,但是我得到999错误-这意味着$this->data为空。在我的控制器中添加函数,它使用POST接收JSON - $this->数据被正确分配。哦,如果我使用POST而不是PUT在我的编辑- $this->数据得到设置,但我不能保存数据..

. .我该怎么做呢?: S

从luchomolina的链接插入http://book.cakephp.org/2.0/en/controllers/request-response.html accessing-xml-or-json-data

//Get JSON encoded data submitted to a PUT/POST action
$data = $this->request->input('json_decode');

你得到了你的对象

$data->Model->field ...

我还没有测试过,但我认为你的数据是在$this->request->input()$this->request->data()

更多信息:

http://book.cakephp.org/2.0/en/controllers/request-response.html accessing-xml-or-json-data

http://book.cakephp.org/2.0/en/controllers/request-response.html CakeRequest::数据