MVC:如何阿贾克斯?MVC、阿贾克斯

2023-09-10 16:00:51 作者:烟酒青年

我要使用Zend框架的MVC实现启动一个项目。

I'm going to start a project using a Zend Framework MVC implementation.

我如何使用Ajax的工作?我的意思是,我应该把所有的Ajax code到控制器?还是进入视野?

How do I work with ajax? I mean, should I place all ajax code into controller? Or into view?

例如,我想从笔者伊万的帖子显示在页面上。

For example, I want to get posts from author 'ivan' to show on a page.

通常情况下,我创建了一个链接到/职位/作家/​​伊万或不服喜欢它,打造'()byAuthorAction的帖子控制器新的行动像(或者用户控制器,别的地方),认为它(和所有code什么的模型得到的职位去那里),并创建一个新的路由。

Normally, I create a link to '/posts/author/ivan' or smth like it, create a new Action like 'byAuthorAction()' in the Posts controller (or maybe Users controller, wherever), view for it (and all code what gets posts from model goes there) and create a new Route to it.

如何将功能添加进去JSON任何用户的帖子,XML格式AJAX,也许API,保持DRY原则和设计code结构,聪明的我可以吗?

How to add functionality to get any user's posts in json, xml formats for ajax and maybe API, keeping the DRY principle and designing the code structure as smart as I can?

-

感谢您的解答! 我会很高兴地看到在像我这样的情况下,设计MVC的意见。我有基本的MVC原则,而不是在更复杂的情况下,一些经验。也许一些有用的链接?

Thanks for answers! I will be very glad to see comments about designing MVC in situations like mine. I have some experience in basic MVC principles but not in more complicated cases. Maybe some useful links?

推荐答案

您真的应该了解ContextSwitch动作助手手册章节。但这里是一个简要介绍:

You really should read the manual chapter about ContextSwitch Action Helper. But here is a brief outline:

在视图脚本(动作name.phtml)用于普通的HTML输出 您可以初始化的一些行动上下文切换控制器使大公可以输出例如XML - XML方面的支持在默认情况下,你会把你的视图脚本对XML的上下文(动作name.xml.phtml); XML方面也禁止布局渲染 在JSON也支持内置的上下文切换和默认选项是关闭布局和视图,并输出所有分配给从JSON格式的控制器动作视图中的变量,这个选项可以通过切换所述setAutoJsonSerialization上下文切换的(假)方法;但如果你打开​​它,你必须创建一个视图脚本动作name.json.phtml和输出用手JSON格式的变量

要两个上下文它们之间进行切换,你必须格式参数添加到您的网址,例如: /职位/作家/​​伊万/格式/ JSON或/职位/作家/​​伊万/格式/ XML。如果没有指定格式的应用程序将输出纯HTML。

To switch between these two contexts you have to add a format parameter to your URL, e.g. /posts/author/ivan/format/json or /posts/author/ivan/format/xml. If you do not specify the format your application will output plain html.

在上下文切换的特殊版本是AjaxContext,你还必须配置这一手。它不使用格式参数来确定哪些格式应该用于输出的,但它会检查你的请求中的标头和查找X-要求,通过:XmlHtt prequest'头,如果它是present的AjaxContext进行检查。使用AjaxContext动作助手,你可以指定哪些方面应该用于具体行动,如果该请求被使用AJAX解雇了。

Special version of the Context switch is AjaxContext and you also have to configure this one by hand. It does not use the 'format' parameter to identify which format it should use for output but it examines the header sent in your request and looks for 'X-Requested-With: XmlHttpRequest' header and if it is present the AjaxContext is examined. Using the AjaxContext action helper you can specify which context should be used for specific actions if the request is fired using AJAX.