Cake PHP restful index方法返回空响应

时间:2017-07-11 19:02:33

标签: php json cakephp cakephp-2.x

我开始学习CakePhp。每当我通过url http://localhost:8888/todolist/entries/index.json打开浏览器时,我都会尝试创建一个安静的应用程序。我没有得到json响应。

   <?php
    App::uses('AppController', 'Controller');
    /**
     * Entries Controller
     *
     * @property Entry $Entry
     * @property PaginatorComponent $Paginator
     */
    class EntriesController extends AppController {

        /**
         * @var array
         */
        public $helpers = array('Html', 'Form');

    /**
     * Components
     *
     * @var array
     */
        public $components = array('Paginator', 'RequestHandler');

    /**
     * index method
     *
     * @return void
     */
        public function index() {
            $this->Entry->recursive = 0;
            $this->set('entries', $this->Paginator->paginate());

            $this->autoRender = false;
            $this->layout = false;
        }
}

这是我的routes.php:

    Router::connect('/', array('controller' => 'entries', 'action' => 'index'));
/**
 * ...and connect the rest of 'Pages' controller's URLs.
 */
    Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

/**
 * Load all plugin routes. See the CakePlugin documentation on
 * how to customize the loading of plugin routes.
 */
    CakePlugin::routes();

/**
 * Load the CakePHP default routes. Only remove this if you do not want to use
 * the built-in default routes.
 */
    require CAKE . 'Config' . DS . 'routes.php';

Router::mapResources('entries');
Router::parseExtensions('json');

以下是firebug的截图。

Firebug Network screenshot

1 个答案:

答案 0 :(得分:1)

您已禁用渲染:

$this->autoRender = false;
因此,您将得到一个空的回复。无需禁用渲染,使用REST和JSON / XML视图文档中描述的序列化视图:

public function index() {
    $this->Entry->recursive = 0;
    $this->set('entries', $this->Paginator->paginate());
    $this->set('_serialize', 'entries'); // that's where the magic begins
}

另见