我爲「應用程序」表創建了一個控制器。 Web和REST界面正在工作,但我認爲添加和編輯功能應該更好。在Contoller中處理REST請求的正確方法
當我測試添加和編輯時,我發現需要以web FORM格式(而不是JSON)發佈數據。
我發現我需要在保存中使用「$ this-> request-> input('json_decode')」來解碼JSON數據。我認爲這是自動發生的。
此功能現在適用於添加(編輯類似)並顯示我的json/add.ctp,因此我可以將成功的記錄返回給用戶。
public function add() {
if ($this->request->is('post')) {
$this->Application->create();
//Is the request REST passing a JSON object?
if (preg_match('/\.json/', $this->request->here)){
//This is a REST call
$this->set('status', $this->Application->save($this->request->input('json_decode')));
} else {
//This is an interactive session
if ($this->Application->save($this->request->data)) {
$this->Session->setFlash(__('The application has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The application could not be saved. Please, try again.'));
}
}
}
}
我使用了「$ this-> request-> here」來查看它是否以「.json」結尾。這是處理REST呼叫的「正確」方式嗎?
我已閱讀並實施它,但它似乎沒有解碼JSON發佈數據。我必須確定它是一個JSON請求並解碼數據。也許我錯過了什麼。 – DuaneW
我需要添加「$ this-> RequestHandler-> addInputType('json',array('json_decode',true));」對我的功能,然後魔術發生。它在RequestHandler doco中。 – DuaneW