Chr*_*sco 3 ajax json cakephp cakephp-2.0
我是 cakePHP 的新手。不用说,我不知道从哪里开始阅读。阅读了几页有关 AJAX 和 JSON 响应的内容,我所能理解的就是我需要使用Router::parseExtensions()and RequestHandlerComponent,但没有一个有我可以阅读的示例代码。
我需要的是调用函数MyController::listAll()并返回Model::find('all')inJSON格式,以便我可以将它与 JS 一起使用。
我需要View为此吗?该视图应该放在哪个文件夹中?它应该有什么扩展名?Router::parseExtension()我应该把和放在哪里RequestHandlerComponent?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道你读了什么,但我猜这不是官方文档。官方文档包含如何执行此操作的示例。
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
// some code that created $posts and $comments
$this->set(compact('posts', 'comments'));
$this->set('_serialize', array('posts', 'comments'));
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用 .json 扩展名调用该操作,您将返回 json,如果使用 .xml 调用该操作,您将返回 xml。
如果您愿意或需要,您仍然可以创建视图文件。该页面上也对此进行了解释。
// Controller code
class PostsController extends AppController {
public function index() {
$this->set(compact('posts', 'comments'));
}
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15997 次 |
| 最近记录: |