在 Zend Framework 中使用 Jquery 的 ajax 功能

发现不少人对此有迷惑,所以有通常的做法:设置 noViewRender,然后将 ajax 调用时的返回数据直接输出于 controller 中。

个人以为,这种做法不是不可以。但是在 Zend Framework 中这样使用,就有违 MVC 的分离原则。controller 不应该区分显示到客户端的是页面还是 json 或者 xml。

下面是我的做法,仅供参考。部分调用了 ninny project 中封装的功能凑合看吧:

———————–view script: index.php—————————

<?php echo $this->jquery();?>
<script language="javascript">
// jquery ajax 的 json
$().ready(
function(){
$("#load").click(
function() {
$.getJSON("/foobar/index/ajax",function(data){
$("#title").html(data.title);
content = "";
$.each(data.content, function(i, line){
content += line + "<br/>";
});
$("#content").html(content);
});
});
});
</script>
<div id="title"></div><div id="content"></div><input type="button" id="load" value="Load"/>
-----------------------view script: ajax.php---------------------------
<?php
// Zend_Json 处理输出的对象,如果这里不使用 Zend_Json,可使用其他编码器将 php 对象进行编码输出。
// 这样在需要修改输出类型时,仅需要修改视图部分。而不涉及数据模型或控制器。
echo Zend_Json::encode($this->content);
?>

———————–action controller: Foobar_IndexController.php—————————

<?php
class Foobar_IndexController extends Ifang_Controller_Action
{
public function indexAction()
{
}
public function ajaxAction()
{
$foobar = array(
'title' => 'This is a test!',
'content' => array(
'0' => 'This is the first line!',
'1' => 'This is the second line!',
'2' => 'This is the last line!',
),
);
// 传递一个普通的 php 对象(变量)到视图。
$this->view->content = $foobar;
}
}

Join the Conversation

2 Comments

  1. 老兄,好久没来你这里了,对于ajax,我用了mootools的工具,在zf中,是直接用了update zf返回的html片段到div中,view因为结合了smarty,写起来要简单方便些。
    在你的ninny项目中,获益良多,真是很感谢。
    acl模块我重新考虑了使用的方法,对你的模型进行了些修改。提供资源继承,角色继承实在有些复杂,在实现前台web时,有些困难,感觉不提供资源继承,角色继承时,要简单好多,且也能很好的满足自定权限的需要。
    不知动态显示权限菜单的你考虑过了没,我想了好久,觉得简单的用一个view helper来实现权限菜单的显示与隐藏也是可以做到的。但我还没实现出来。

  2. 实际上,我现在 top 部分的 navbar 就是权限动态控制的。用 js 或 div + css 按同样原理实现下拉菜单方式,应该不困难。
    使用资源、角色继承大概主要是因为我以前主要在信息系统上开发。所以比较习惯这种设计。当然,这样虽然功能好,但是也比较复杂。

    没有使用 smarty 的原因,主要是考虑到 php 本身就是一个极好的模板语言,而工作中也很少需要美工协助页面编写。另外,用 Zend Framework 的 view 并对关键功能用 helper 进行封装效果也不错。可以试一试。其实对于美工来说 foreach 和 selection 看起来都差不多。 ^_^

Leave a comment

Your email address will not be published. Required fields are marked *