ajax - 使用 CakePHP 的简单 AJAX/JSON 响应

标签 ajax json cakephp cakephp-2.0

我是 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/

相关文章:

cakephp - CakePHP Controller 中的 add 方法不起作用

php - CakePHP 模型是否可以在不重新实例化的情况下更改其表?

jquery - 从 jquery ajax 调用返回

c++ - 我不希望 JSON 在 C++ 中转义撇号。如何解决这个问题?

javascript - 从使用 jqplot 的网站上的绘图中获取原始数据

php - 使用 cakephp 3 根据第二个表从数据库中查找记录

jquery - 如何在mvc中使用防伪 token 发出ajax请求

对 Sinatra 应用程序的 JQuery AJAX 请求被 CORS 阻止

jquery - 如何在Asp.Net MVC中通过jquery ajax动态加载部分 View

javascript - jquery移动网络应用程序开发(需要帮助)