Creating a custom JSON response object with Zend Action Helper ContextSwitch

删除回忆录丶 提交于 2019-12-18 13:19:17

问题


I normally append an encoded json object to the response body, however I now have a situation that warrants using the ContextSwitch action helper.

I have a Zend_Form that requires three different response contexts:

  1. html - Render the form as normal html within a layout.
  2. html-partial - An ajax "get" request that renders just the form as html.
  3. json - An ajax "post" request that returns any form valiation error messages.

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

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?


回答1:


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();

And In my indexAction():

if ( true === $this->isAjaxJson() ) {
    $this->_helper->json(
        array(
            'response' => $myResponse,
            'message' => $myMesage
        )
    );
    return;
}

Hope this help.




回答2:


this may help : $this->_helper->json->sendJson($data); while,

$data=array('data1'=>'val1','data2'=>'val2');



来源:https://stackoverflow.com/questions/5231584/creating-a-custom-json-response-object-with-zend-action-helper-contextswitch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!