Zend框架清洁Ajax控制器的实现 [英] Clean Ajax controller implementation in Zend Framework

查看:149
本文介绍了Zend框架清洁Ajax控制器的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个控制器在我的Zend框架项目,该项目应只处理Ajax请求。

I need a controller in my Zend Framework project, which should handle only ajax requests.

我此刻的方法是延长依靠Zend_Controller_Action:

My approach at the moment is to extend the Zend_Controller_Action:

class Ht_Ajax_Controller extends Zend_Controller_Action{
    public function preDispatch(){
        $this->getResponse()->setHeader('Content-type', 'text/plain')
                            ->setHeader('Cache-Control','no-cache');
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout()->disableLayout();
    }

    public function outputJson($data){
        $this->getResponse()->setBody(json_encode($data))
                            ->sendResponse();
        exit;
    }
}

虽然,我知道这是不推荐的方法,这样做Zend框架。所以这就是为什么我要问,如何使这个在Zend的方式?

Although, I know this isn't the recommended way to do so in Zend Framework. So that's why I am asking, how to make this in Zend's way ?

我想到的第一件事是让控制器插件,但我怎么能轻松地注册这个插件?自举是没办法,因为我需要这个只针对特定的控制器。并似乎登记在一个非常早期的状态,控制器内不是很干净。

The first thing I thought about was to make a controller plugin, but how can I register this plugin easily? The bootstrap is no option because I need this only for specific controllers. And to register it inside the controller in a very early state seems not very clean.

所以,我应该怎么实现我的Ajax控制器?我也知道有扩展的上下文切换帮手,但是我觉得这种方式有太多的开销,只设置内容类型等。

So how should I implement my Ajax Controller? I also know there is the extended Context switching helper ,however I think that way has too much overhead for just setting the content type etc.

推荐答案

马库斯解释最Zend的像方式他的解释是正确的。但是你看它太多的开销,因为他错过了向您展示了JSON上下文切换多少是最适合你的情况。

markus explained the most "Zend Like" way and his explanation is correct. But you see it as too much overhead because he missed to show you how much the "json context switch" is the best for your case.

看看它是如何简而言之就是:

Look how short it is :

//In your controller, activate json context for ANY called action in once

public function init(){
    $action = $this->_getParam('action');
    $this->_helper->getHelper('contextSwitch')
         ->addActionContext($action, 'json')
         ->initContext();
}

,并通过多数民众赞成,你不需要任何视图脚本,所有的分配变量 $这个 - >查看将序列化为一个JSON对象。

And thats all, you don't need any view scripts, all the variables you assign via $this->view will be serialized into a JSON object.

呵呵,你不希望添加上下文中的网址吗?好吧,只要激活它默认在您的路线

Oh and you don't want to add the context in the urls? Ok, just activate it by default in your route

routes.ajax.route = '/ajax/:action/*'
routes.ajax.defaults.controller = ajax
routes.ajax.defaults.action = index
routes.ajax.defaults.format = json

这篇关于Zend框架清洁Ajax控制器的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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