【问题标题】:Creating a custom JSON response object with Zend Action Helper ContextSwitch使用 Zend Action Helper ContextSwitch 创建自定义 JSON 响应对象
【发布时间】:2011-07-11 00:51:26
【问题描述】:

我通常将一个编码的 json 对象附加到响应正文中,但是我现在有一种情况需要使用 ContextSwitch 操作助手。

我有一个需要三种不同响应上下文的 Zend_Form:

  1. html - 将表单呈现为普通 html 在一个布局内。
  2. html-partial - 呈现的 ajax “获取”请求 只是 html 格式的表单。
  3. json - 返回的 ajax “发布”请求 任何表单验证错误消息。

对于每个上下文,我有 3 个视图脚本。虽然这两个 html 上下文可以使用相同的视图脚本,但我还没有弄清楚这是否可能。

  • form.phtml
  • form.html.phtml
  • form.json.phtml

html 上下文视图工作正常,但 json 视图没有被拾取。覆盖默认 json 后回调行为或将自定义编码对象传递给响应正文的最佳方法是什么?

【问题讨论】:

  • 我发现在 contextSwitch 上设置 setAutoJsonSerialization(false) 允许渲染视图脚本,同时仍保留上下文 Content-Type 标头。

标签: php json zend-framework helper context-switch


【解决方案1】:

这可能会有所帮助: $this->_helper->json->sendJson($data); 同时,

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

【讨论】:

    【解决方案2】:

    就我个人而言,我不使用“视图”来生成 JSON 内容。 在我的init() 中,我有这样的东西:

    $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;
    }
    

    希望对您有所帮助。

    【讨论】:

    • 是的,这或多或少是我的做法。但是我使用了一个单独的视图脚本来处理响应。
    猜你喜欢
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多