php - 使用 Zend Action Helper ContextSwitch 创建自定义 JSON 响应对象

标签 php json zend-framework helper context-switch

我通常将一个编码的 json 对象附加到响应主体,但是我现在遇到了需要使用 ContextSwitch 操作助手的情况。

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

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

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

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

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

最佳答案

就我个人而言,我不使用“View”来生成 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;
}

希望这对您有所帮助。

关于php - 使用 Zend Action Helper ContextSwitch 创建自定义 JSON 响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5231584/

相关文章:

php - Curl 请求损坏 XML 发布数据

c# - 使用 JavaScriptSerializer 反序列化 JSON

javascript - 将 JSON 数据编辑为 Firebase 格式

php - 为什么 DOCUMENT_ROOT 与远程服务器上的实际路径 ('.' 不同)

php - AWS SNS 推送通知说明

php - 检查 PHP 语法错误?

python - 使用 Python 的多个属性直接在字典或 json 对象中定位元素

php - Zend_Cache::throwException ('Invalid backend...' ) magento

php - htaccess 意外重定向到文件夹

php - 处理重音字符