我有一些数据想要用来构建表单的选择字段。生成表单的 JS(它是 jqgrid 插件的一部分)位于 View 中。如何将数据从 Controller 获取到 JavaScript 中以便我可以使用它?
为了让某些东西正常工作,我尝试了以下操作...
在 Controller 中,我创建了一个操作来返回一些示例数据:
public function testAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$a = "0:Select";
return Zend_Json::encode($a);
}
在 View 中,我对该操作进行 ajax 调用:
var testselect = $.ajax({
url: '/admin/sites/test',
dataType: "json",
complete: function(data) {
console.log(data);
}
});
这会返回一个 XMLHTTPRequest 对象,其中部分包含:
responseText:""
status:200
statusText:"OK"
responseText 不应该是调用 /admin/sites/test
返回的内容吗?
在我看来,这就是正在发生的事情:
- View 向管理模块中站点 Controller 的测试操作发出 ajax 请求
- 测试操作 JSON 对
$a
的内容进行编码并返回 testselect
的complete
回调函数将结果记录到控制台,并且应在responseText 中包含
。$a
的内容
我哪里理解错了?有一个更好的方法吗?就像, Controller 可以将所需的数据传递给 View 对象,然后我以某种方式在 javascript 中访问它(尽管如何,而不发出 ajax 请求或将数据放入像 $_SESSION 这样的超全局中,我不知道)? p>
感谢任何帮助。
最佳答案
试试这个:
public function testAction() {
$data = array('firstname' => 'Benny', 'surname' => 'Hill');
$this->_helper->json($data);
}
请参阅section about the json action helper在文档中。
您还可以阅读有关 the action helpers ContextSwitch
and AjaxContext
的部分
关于php - Zend Framework - 在 Controller 中生成数据并传递给 View 以在 Javascript 中使用。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722194/