最简单的方式是使用上下文切换。在你的控制器,安装在AjaxContext助手为您的操作与“JSON”上下文
class EntryController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->ajaxContext->addActionContext('get-member-course', 'json')
->initContext();
}
public function getMemberCourseAction()
{
$id = $this->_getParam('id');
$this->view->test = array('test' => 'bleh');
}
}
用于调用脚本视图应包含对JSON URL的参考。例如,假设您的JSON代码通过单击链接而解雇了,像这样创建
<a id="get-json" href="<?php echo $this->url(array(
'action' => 'get-member-course',
'controller' => 'entry',
'id' => $someId
), null, true) ?>">Click me for JSON goodness</a>
你的客户端代码的链接将有这样的事情
$('#get-json').click(function() {
var url = this.href;
$.getJSON(url, {
"format": "json" // this is required to trigger the JSON context
}, function(data, textStatus, jqXHR) {
// handle response here
});
});
默认情况下,JSON上下文被触发,任何视图属性被序列化为JSON并在响应中返回。如果您的视图属性不能简单地转换,你需要禁用自动JSON序列...
$this->_helper->ajaxContext->addActionContext('my-action', 'json')
->setAutoJsonSerialization(false)
->initContext();
,并提供一个JSON视图脚本
// controllers/my/my-action.json.phtml
$simplifiedArray = array(
'prop' => $this->someViewProperty->getSomeValue()
);
echo Zend_Json::encode($simplifiedArray);
看到我更新的答案。另外,显示您的客户端脚本 – Phil