我是 cakePHP 的新手。不用说我不知道从哪里开始阅读。阅读有关 AJAX 和 JSON 响应的几页,我所能理解的是我需要以某种方式使用 Router::parseExtensions()
和 RequestHandlerComponent
,但没有一个有示例代码可以阅读。
我需要调用函数 MyController::listAll()
并在 JSON
中返回一个 Model::find('all')
> 格式化以便我可以将它与 JS 一起使用。
为此我需要一个 View
吗?
该 View 应该放在哪个文件夹中?
它应该有什么扩展名?
我应该把 Router::parseExtension()
和 RequestHandlerComponent
放在哪里?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
最佳答案
我不知道你读到了什么,但我猜它不是 the official documentation .官方文档包含如何操作的示例。
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'));
}
}
如果使用 .json 扩展调用操作,您将返回 json,如果使用 .xml 调用操作,您将返回 xml。
如果您愿意或需要,您仍然可以创建 View 文件。 Its as well explained on that page .
// 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'));
关于ajax - 使用 CakePHP 的简单 AJAX/JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246063/