使用 Zend Action Helper ContextSwitch 创建自定义 JSON 响应对象
我通常会在响应正文中附加一个编码的 json 对象,但是现在我遇到了需要使用 ContextSwitch 操作助手的情况.
I normally append an encoded json object to the response body, however I now have a situation that warrants using the ContextSwitch action helper.
我有一个 Zend_Form 需要三个不同的响应上下文:
I have a Zend_Form that requires three different response contexts:
- html - 将表单呈现为普通的 html在布局内.
- html-partial - 呈现的 ajaxget"请求只是表单为 html.
- json - 返回的 ajaxpost"请求任何形式验证错误消息.
- html - Render the form as normal html within a layout.
- html-partial - An ajax "get" request that renders just the form as html.
- json - An ajax "post" request that returns any form valiation error messages.
对于每个上下文,我有 3 个视图脚本.虽然这两个html上下文可以使用同一个视图脚本,但是我还没有弄清楚这是否可能.
For each context I have 3 view scripts. Although the two html contexts could use the same view script, but I haven't figured out if this is possible.
- form.phtml
- form.html.phtml
- form.json.phtml
html 上下文视图可以正常工作,但是 json 视图没有被选中.覆盖默认 json post 回调行为或将自定义编码对象传递给响应正文的最佳方法是什么?
The html context views work okay, but the json view is not being picked up. What is the best method to override the default json post callback behaviour or pass a custom encoded object to the response body?
推荐答案
就我个人而言,我不使用视图"来生成 JSON 内容.在我的 init()
中,我有这样的东西:
Personally, I don't use "View" to generate JSON content.
In my init()
, I have something like this:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->setAutoJsonSerialization(false)
->addActionContext('index', array('html', 'json'))
->initContext();
在我的indexAction()
中:
if ( true === $this->isAjaxJson() ) {
$this->_helper->json(
array(
'response' => $myResponse,
'message' => $myMesage
)
);
return;
}
希望对您有所帮助.
相关文章