ZendFramework2學習筆記 json和ajax

來源:互聯網
上載者:User

標籤:zendframework2   layout   mvc   json   ajax   

    要實現zf2的控制器輸出json資料,主要要解決2個問題,第一個就是修改header頭的Content-type部分為

‘Content-Type: application/json‘,第二個就是輸出json資料。

    修改header頭,可以手動修改也可以自動修改。

    自動修改的方式是,使用zf2的JsonRenderer,或者json的view helper:

    1)使用JsonRenderer的方法:zf2預設使用PhpRender,因此需要在項目啟動的時候,修改renderer。在啟動模組(Application)的onBootStrap方法中,添加一個render事件的linstener(registerJsonStratery),   

    public function onBootstrap($e)    {        // Register a render event        $app = $e->getParam('application');        $app->getEventManager()->attach('render', array($this, 'registerJsonStrategy'), 100);    }

    在lisntener中將jsonStratery sttach到View的EventManger上,

    public function registerJsonStrategy($e)    {        $matches    = $e->getRouteMatch();        $moduleRootName = $matches->getMatchedRouteName();//$moduleaRootName是在module.config.php中配置的route名稱        if ($moduleRootName != 'test') { //該模組所有控制器都設定為JsonRenderer            return;        }        $app          = $e->getTarget();        $locator      = $app->getServiceManager();        $view         = $locator->get('Zend\View\View');        $jsonStrategy = $locator->get('ViewJsonStrategy');        $view->getEventManager()->attach($jsonStrategy, 100);    }

    2)使用view helper的方法:在控制器裡面禁用layout($view->setTerminal(true);)或者在layout裡面不要輸出任何html,然後view裡面json輸出,

$arr = array();$arr[] = 1111;$arr[] = 'aaaa';echo $this->json($arr);

    手動修改header頭的方式,在view裡面(禁用layout)或者在layout裡面輸出,

header('Content-Type: application/json');

    zf2提供了json編解碼類Zend\Json\Json用於json資料編解碼,該類會先嘗試使用php函數json_encode和json_decode進行編解碼,如果php不支援這2個函數,該類則會使用php指令碼進行編解碼,因此,在zf2中盡量使用該類而不要使用php的json_encode和json_decode進行編解碼。
    例子1:讓單個控制器的action輸出json,

    方法一:

//控制器代碼use Zend\Json\Json;//.......$arr = array();$arr[] = 1111;$arr[] = 'aaaa';$jsonData = Json::encode($arr);        $view =  new ViewModel(array(    'jsonData' => $jsonData));$view->setTerminal(true);return $view;//或者$arr = array();$arr[] = 1111;$arr[] = 'aaaa';       $view =  new ViewModel(array(    'arr' => $arr));return $view;//視圖代碼header('Content-Type: application/json');echo $this->jsonData;//或者echo $this->json($this->arr);


    方法二:建立一個layout檔案如下,

//view/layout/json.phtmlheader('Content-Type: application/json');

    控制器代碼,

use Zend\Json\Json;//.......$layout = $this->layout();$layout->setTemplate('layout/json');$arr = array();$arr[] = 1111;$arr[] = 'aaaa';$jsonData = Json::encode($arr);         $view =  new ViewModel(array(    'jsonData' => $jsonData));return $view;

    視圖代碼,

echo $this->jsonData;

    例子2:讓某個模組或者某個控制器都輸出json,將renderer改為JsonRenderer並且更換預設的php layout後,就直接在view中輸出json資料了,

    public function onRoute(MvcEvent $e)    {        $matches    = $e->getRouteMatch();        $moduleRootName = $matches->getMatchedRouteName();//$moduleaRootName是在module.config.php中配置的route名稱                if ($moduleRootName != 'test') { //該模組所有控制器都設定為JsonRenderer            return;        }        $controllerName = $matches->getParam('controller');//$controllerName是在module.config.php中配置的controller名稱if ($controllerName != 'Test\Controller\Test') { //該控制器所有actions都設定為JsonRenderer            return;        }                $e->getViewModel()->setTemplate("layout/json");      }        public function onBootstrap(MvcEvent $e)    {        $eventManager        = $e->getApplication()->getEventManager();        $moduleRouteListener = new ModuleRouteListener();        $moduleRouteListener->attach($eventManager);                $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -9000);        $eventManager->attach('render', array($this, 'registerJsonStrategy'), 100);    }        public function registerJsonStrategy($e)    {        $matches    = $e->getRouteMatch();        $moduleName = $matches->getMatchedRouteName();        $matches    = $e->getRouteMatch();        $moduleRootName = $matches->getMatchedRouteName();//$moduleaRootName是在module.config.php中配置的route名稱                if ($moduleRootName != 'test') { //該模組所有控制器都設定為JsonRenderer            return;        }        $controllerName = $matches->getParam('controller');//$controllerName是在module.config.php中配置的controller名稱if ($controllerName != 'Test\Controller\Test') { //該控制器所有actions都設定為JsonRenderer            return;        }                $app          = $e->getTarget();        $locator      = $app->getServiceManager();        $view         = $locator->get('Zend\View\View');        $jsonStrategy = $locator->get('ViewJsonStrategy');        $view->getEventManager()->attach($jsonStrategy, 100);            }

    之後,就可以直接在瀏覽器端的javascript中通過ajax擷取json資料了:
<script lang="javascript">    $(document).ready(function(){        $("#b01").click(function(){            htmlobj=$.ajax({url:"/test/json",async:false});            alert(htmlobj.responseText);        });    });    </script>








ZendFramework2學習筆記 json和ajax

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.