1

我已经阅读了很多关于此的内容,但我仍然不确定我的实现是否正确,因为我没有来自应用程序的反馈......我已将以下代码添加到 routes.php

路由器::mapResources('posts'); 路由器::parseExtensions('json');

以及控制器 PostsController.php 上的以下代码

class PostsController extends AppController {
public $helpers = array('Html', 'Form');
var $components = array('RequestHandler');

public function index() {
    $this->set('posts', $this->Post->find('all'));
}

public function view($id = null) {
    $this->Post->id = $id;
    $this->set('post', $this->Post->read());
    $this->set(compact('posts'));
}

public function add() {
    if ($this->request->is('post')) {
        if ($this->Post->save($this->request->data)) {
            $this->set(compact('posts'));
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}

public function edit($id = null) {
    $this->Post->id = $id;
    if ($this->request->is('get')) {
        $this->request->data = $this->Post->read();
    } else {
        if ($this->Post->save($this->request->data)) {
            $this->set(compact('posts'));
            $this->Session->setFlash('Your post has been updated.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to update your post.');
            }
        }
}
public function delete($id) {
if ($this->request->is('get')) {
    throw new MethodNotAllowedException();
}
    if ($this->Post->delete($id)) {
        $this->set(compact('posts'));
        $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
        $this->redirect(array('action' => 'index'));
    }
}

}

这够了吗?我的目标是让一个 android 应用程序通过这个 web 服务与 MySQL 数据库通信。希望你能帮我 :/

4

1 回答 1

0

感谢 Costa,我能够让 REST 正常工作(我认为 XD)我使用了一个插件,因为他建议测试它,但我只能从http://localhost:3030/cake_2_1/posts/index收到正确的答案.json 在 coockbook 他们有 POST /recipes.format RecipesController::add() 来添加一些东西,但它如何在这里转换成一个 url?echo json_encode($message);是我在 View\Posts\json\add.ctp 和

if ($this->Post->save($this->request->data)) { $message = 'Saved'; } else { $message = 'Error'; } $this->set(compact("message")); 是我在控制器添加功能中所拥有的。快完成了,只需要多一点帮助:)

于 2012-04-20T01:39:58.010 回答