3

通过 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 的回调函数!值得一提的是,并非所有 url 都有自定义路由。

请帮忙,因为我几乎将退出使用 Zend 框架的开发!

4

2 回答 2

1

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')没有运行?

于 2012-05-20T17:09:38.250 回答
1

在行动中,你只需要使用

$this->_helper->json($appPrivArray)

你不需要使用setNoRender或其他任何东西。在 Javascript 中你不需要使用dataType: 'JSON', 我测试过的,应该可以正常工作。

于 2012-05-20T17:20:09.120 回答