問題描述
我通常會在響應(yīng)正文中附加一個(gè)編碼的 json 對象,但是現(xiàn)在我遇到了需要使用 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.
我有一個(gè) Zend_Form 需要三個(gè)不同的響應(yīng)上下文:
I have a Zend_Form that requires three different response contexts:
- html - 將表單呈現(xiàn)為普通的 html在布局內(nèi).
- html-partial - 呈現(xiàn)的 ajaxget"請求只是表單為 html.
- json - 返回的 ajaxpost"請求任何形式驗(yàn)證錯(cuò)誤消息.
- 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.
對于每個(gè)上下文,我有 3 個(gè)視圖腳本.雖然這兩個(gè)html上下文可以使用同一個(gè)視圖腳本,但是我還沒有弄清楚這是否可能.
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 視圖沒有被選中.覆蓋默認(rèn) json post 回調(diào)行為或?qū)⒆远x編碼對象傳遞給響應(yīng)正文的最佳方法是什么?
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?
推薦答案
就我個(gè)人而言,我不使用視圖"來生成 JSON 內(nèi)容.在我的 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;
}
希望對您有所幫助.
這篇關(guān)于使用 Zend Action Helper ContextSwitch 創(chuàng)建自定義 JSON 響應(yīng)對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!