使用CakePHP的简单AJAX/JSON响应 [英] Simple AJAX / JSON response with CakePHP

查看:209
本文介绍了使用CakePHP的简单AJAX/JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是CakePHP的新手.不用说,我不知道从哪里开始阅读.阅读关于AJAX和JSON响应的几页内容,我所能理解的就是我需要使用Router::parseExtensions()RequestHandlerComponent,但是没有一个示例代码可以读取.

I'm new to cakePHP. Needless to say I don't know where to start reading. Read several pages about AJAX and JSON responses and all I could understand is that somehow I need to use Router::parseExtensions() and RequestHandlerComponent, but none had a sample code I could read.

我需要调用函数MyController::listAll()并以JSON格式返回Model::find('all'),以便可以与JS一起使用.

What I need is to call function MyController::listAll() and return a Model::find('all') in JSON format so I can use it with JS.

我需要一个View吗? 该视图应该放在哪个文件夹中? 它应该有什么扩展名? Router::parseExtension()RequestHandlerComponent放在哪里?

Do I need a View for this? In what folder should that view go? What extension should it have? Where do I put the Router::parseExtension() and RequestHandlerComponent?

// Controller
public function listAll() {
    $myModel = $this->MyModel->find('all');

    if($this->request->is('ajax') {
        $this->layout=null;

        // What else?

    }
}

推荐答案

我不知道您阅读了什么,但我想它不是

I don't know what you read but I guess it was not the official documentation. The official documentation contains examples how to do it.

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.

If the action is called with the .json extension you get json back, if its called with .xml you'll get xml back.

如果需要,您仍然可以创建视图文件. 在该页面上也有说明.

If you want or need to you can still create view files. 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'));

这篇关于使用CakePHP的简单AJAX/JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆