`

cakephp jquery ajax json

阅读更多
简介

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。Cakephp1.2提供了对JSON的内置支持,主要体现在两个特殊的方法:

Router::parseExtensions() 和 JavascriptHelper::object()

目标

我们要通过JQuery的$.getJSON方法,获取Cakephp服务端的JSON数据,URL可能是这个样子
1.http://localhost/posts/index.json

如何完成?

首先,要让Cakephp启用JSON的扩展名解析

编辑/config/routes.php,添加
1.Router::parseExtensions(’json’);

然后,为JSON设置Content-type

编辑app_controller.php,添加
var $components = array('RequestHandler');
function beforeFilter() {
    $this->RequestHandler->setContent('json', 'text/x-json');
    parent::beforeFilter();
}

RequestHandler的setContent方法,可以使json的扩展名使用特定的layout和视图,就像下面的代码

下面,为你的JSON数据创建一个layout

创建/layouts/json/default.ctp的代码
<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: text/x-json');
header("X-JSON: ".$content_for_layout);

echo $content_for_layout;
?>

注意:

在使用RequestHandler的setContent方法后,Cakephp会自动解析json扩展名的访问并且会默认使用

/layouts/json/default.ctp解析json,如果不存在这个layout的话,会出现 未找到layout 错误.

x-json头可以被prototype.js将返回的数据自动解析为JSON对象

下面创建我们的JSON视图

创建/views/posts/json/index.ctp的代码 (注意加粗的部分)
< ?php
echo $javascript->object($aPosts);
?>

同样的json也有自己的视图文件,简单理解就是,在你的控制器视图下的json文件夹,建立同名的视图文件.

控制器中的代码
function index() {

        Configure::write('debug',0); //不加这一句 jquery获取 json数据时 无法获取 默认的debug页面会破坏json的数据结构,切记一定要加上

    $this->set('aPosts', $this->Post->findAll());
}

在JQuery中使用

假如我们的返回值类似下面这样
Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 1
                    [user_id] => 54
                    [subject] => augue scelerisque mollis.
                    [body] => tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet magna
                    [created] => 2009-10-29 21:15:51
                )

        )

    [1] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [user_id] => 81
                    [subject] => purus, in molestie tortor nibh
                    [body] => elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec urna suscipit nonummy.
                    [created] => 2009-08-01 06:57:03
                )

        )

)

我们可以这样使用JSON数据
$.getJSON("http://localhost/posts/index.json", function(json){
  alert(json[0].Post.subject);
  alert(json[1].Post.subject);
});

可以看到,我们可以直接使用由json返回的数据,而不用做任何转换.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics