ZENDFRAMEWORK2 Learning notes JSON and Ajax

Source: Internet
Author: User
Tags zend

To implement the ZF2 controller output JSON data, mainly to solve 2 problems, the first is to modify the header of the Content-type section

' Content-type:application/json ', the second is the output of JSON data.

Modify header headers, which can be modified manually or automatically.

The automatic modification is by using Zf2 's jsonrenderer, or the JSON View helper:

1) Use Jsonrenderer method: Zf2 uses Phprender by default, so you need to modify the renderer when the project starts. In the Onbootstrap method of the Boot module (application), add a Linstener (registerjsonstratery) of the render event,

    Public Function Onbootstrap ($e)    {        //Register A render event        $app = $e->getparam (' application ');        $app->geteventmanager ()->attach (' Render ', array ($this, ' registerjsonstrategy '), +);    }

In Lisntener the Jsonstratery Sttach to the Eventmanger of the view,

    Public Function Registerjsonstrategy ($e)    {        $matches    = $e->getroutematch ();        $moduleRootName = $matches->getmatchedroutename ();//$moduleaRootName is the route name configured in module.config.php        if ($ Modulerootname! = ' Test ') {//The module all controllers are set to Jsonrenderer            return;        }        $app          = $e->gettarget ();        $locator      = $app->getservicemanager ();        $view         = $locator->get (' Zend\view\view ');        $jsonStrategy = $locator->get (' viewjsonstrategy ');        $view->geteventmanager ()->attach ($jsonStrategy, +);    }

2) Use the View helper method: Disable layout in the controller ($view->setterminal (true), or do not output any HTML in layout, and then view the JSON output,

$arr = Array (), $arr [] = 1111; $arr [] = ' aaaa '; Echo $this->json ($arr);

Manually modify header headers in the view (disable layout) or output in layout,

Header (' Content-type:application/json ');

ZF2 provides JSON codec class Zend\json\json for JSON data codec, the class will first try to use PHP functions Json_encode and Json_decode for codec, if PHP does not support these 2 functions, This class is encoded using PHP scripts, so try to use the class in ZF2 instead of using PHP's Json_encode and Json_decode for encoding and decoding.
Example 1: Let the action of a single controller output JSON,

Method One:

Controller code 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;//or $arr = Array (); $arr [] = 1111; $arr [] = ' aaaa ';       $view =  New ViewModel (Array (    ' arr ' = $arr); return $view;//View Code header (' Content-type:application/json '); echo $this->jsondata;//or Echo $this->json ($this->arr);


Method Two: Create a new layout file as follows,

View/layout/json.phtmlheader (' Content-type:application/json ');

Controller code,

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;

View Code,

Echo $this->jsondata;

Example 2: Let a module or a controller output JSON, change renderer to Jsonrenderer and replace the default PHP layout, directly in the view of the output JSON data,

    Public Function Onroute (mvcevent $e) {$matches = $e->getroutematch (); $moduleRootName = $matches->getmatchedroutename ();//$moduleaRootName is the route name configured in module.config.php if ($        Modulerootname! = ' Test ') {//The module all controllers are set to Jsonrenderer return; } $controllerName = $matches->getparam (' controller '),//$controllerName is the controller name configured in module.config.php if ($c        Ontrollername! = ' test\controller\test ') {//The controller all actions are set to jsonrenderer return;      } $e->getviewmodel ()->settemplate ("Layout/json"); The Public Function onbootstrap (mvcevent $e) {$eventManager = $e->getapplication ()->geteventm        Anager ();        $moduleRouteListener = new Moduleroutelistener ();                $moduleRouteListener->attach ($eventManager);        $eventManager->attach (Mvcevent::event_route, Array ($this, ' Onroute '),-9000); $eventManager->attach (' Render ', array ($this, ' RegisTerjsonstrategy '), 100);        The Public Function Registerjsonstrategy ($e) {$matches = $e->getroutematch ();        $moduleName = $matches->getmatchedroutename ();        $matches = $e->getroutematch (); $moduleRootName = $matches->getmatchedroutename ();//$moduleaRootName is the route name configured in module.config.php if ($        Modulerootname! = ' Test ') {//The module all controllers are set to Jsonrenderer return; } $controllerName = $matches->getparam (' controller '),//$controllerName is the controller name configured in module.config.php if ($c        Ontrollername! = ' test\controller\test ') {//The controller all actions are set to jsonrenderer return;        } $app = $e->gettarget ();        $locator = $app->getservicemanager ();        $view = $locator->get (' Zend\view\view ');        $jsonStrategy = $locator->get (' viewjsonstrategy ');            $view->geteventmanager ()->attach ($jsonStrategy, 100); }

You can then get the JSON data through Ajax directly in the browser-side javascript:
<script lang= "JavaScript" >    $ (document). Ready (function () {        $ ("#b01"). Click (function () {            htmlobj= $.ajax ({url: "/test/json", Async:false});            Alert (htmlobj.responsetext)    ;}); </script>








ZENDFRAMEWORK2 Learning notes JSON and Ajax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.