2012-05-20 19 views
3

當通過AJAX發送請求時,如何停止佈局渲染.. 我面對的問題是json數據在瀏覽器上回顯,而不是傳遞給回調函數jquery停止使用自定義路由的Ajax請求的佈局渲染

,這裏是我的腳本

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框架的開發!

回答

1

在操作,你只需要使用

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

你並不需要使用setNoRender或其他任何東西。 而在Javascript中,你不需要使用dataType: 'JSON', 我測試了這個,應該可以正常工作。

+0

我把所有評論drew010 answer.please檢查出來。 – palAlaa

+1

如果仍然得到佈局,則存在一種可能性,即操作中存在錯誤,並且佈局顯示異常消息和堆棧跟蹤,而不僅僅返回json。你有沒有檢查過返回的代碼,看看是否有任何異常消息? – Salman

+0

我面臨的問題是在路由中,我有兩個同名的路由,所以這是問題.. – palAlaa

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')不能運行?

+0

現在js中發生錯誤,並警告此<! - application/layouts/scripts/layout.phtml - >和佈局的整個html! – palAlaa

+0

@Salman,我照你說的做,現在它警惕你好,胸圍仍然提醒佈局腳本! – palAlaa

+0

我提醒('hello'+特權);它提醒佈局頁面 – palAlaa