通过 AJAX 发送请求时,如何停止布局渲染。我面临的问题是json数据在浏览器上回显,而不是传递给jquery的回调函数
这是我的脚本
jQuery.ajax({
url: "/getPrivileges",
type: "POST",
dataType: 'JSON',
success: function(privileges){
alert('hellooo');
buildTree(privileges,".privBox h2");
if($(".privPrivilege"))
$("#loading").css("visibility","hidden");
},
error: function (request, status, error) {
alert('Error'+request.responseText);
}
});
这是路由
resources.router.routes.privilege.route = /getPrivileges
resources.router.routes.privilege.defaults.module = privileges
resources.router.routes.privilege.defaults.controller = privilege
resources.router.routes.privilege.defaults.action = get-privileges
这是我的控制器
public function getPrivilegesAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
...........
...........
$this->_helper->json($appPrivArray);
$this->_helper->viewRenderer->setNoRender(TRUE);
$this->_helper->layout->disableLayout();
$response = $this->getResponse();
$response->setHeader('Content-type', 'application/json', true);
}
}
首先,我面对仍然呈现的布局,但现在json打印在屏幕上,即使我没有get-privileges.phtml视图页面。
在控制器的 init(( 方法中,我这样做
public function init() {
$ajaxContextSwitch = Zend_Controller_Action_HelperBroker::getStaticHelper('AjaxContext');
$ajaxContextSwitch->setDefaultContext('json');
$ajaxContextSwitch->addActionContext('getPrivileges', 'json');
$ajaxContextSwitch->initContext();
}
如何让响应传递到 jQuery 的回调函数!值得一提的是,并非所有网址都有自定义路由。
请帮忙,因为我几乎要退出使用 Zend 框架的开发了!!
在操作中,你只需要使用
$this->_helper->json($appPrivArray)
您不需要使用setNoRender
或其他任何东西。在Javascript中,你不需要使用dataType: 'JSON',
我测试了这个,应该可以正常工作。
JSON 数据通过"在浏览器上回显"返回到 jQuery(或任何其他库(。 这就是回调接收数据的方式。
JSON 视图帮助程序会为您禁用布局,并将Content-Type
标头设置为 application/json
因此您不必这样做。
如果没有给定操作的视图脚本,则可以继续使用 setNoRender(true)
。
我认为这段代码应该可以正常工作:
public function getPrivilegesAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
$this->_helper->viewRenderer->setNoRender(TRUE);
$this->_helper->json($appPrivArray);
}
}
您是否收到任何 Javascript 错误或alert('hello')
未运行?