code: public function onRoute(MvcEvent $event)
      {
          /* @var \Zend\Http\PhpEnvironment\Request $request */
          $request = $event->getRequest();
          $ajax = $request->getQuery()->get('ajax');
  
          if (!$request->isXmlHttpRequest() || !$ajax) {
              /* no ajax request or required parameter not present */
              return;
          }
  
          /* @var \Zend\Http\PhpEnvironment\Response $response */
          /* @var AjaxEvent $ajaxEvent */
          $response = $event->getResponse();
          
          $ajaxEvent = $this->ajaxEventManager->getEvent($ajax, $this);
          $ajaxEvent->setRequest($request);
          $ajaxEvent->setResponse($response);
  
          $results = $this->ajaxEventManager->triggerEventUntil(function ($r) {
              return null !== $r;
          }, $ajaxEvent);
          $result  = $results->last() ?: $ajaxEvent->getResult();
  
          if (!$result) {
              throw new \UnexpectedValueException('No listener returned anything. Do not know what to do...');
          }
  
          /* Convert arrays or traversable objects to JSON string. */
          if (is_array($result) || $result instanceof \Traversable) {
              $result = Json::encode($result, true, ['enableJsonExprFinder' => true]);
          }
  
          $contentType = $ajaxEvent->getContentType();
  
          $response->getHeaders()->addHeaderLine('Content-Type', $contentType);
          $response->setContent($result);
  
          return $response;
      }
docs: Handler for onRoute mvc event.
  
  @param MvcEvent $event
  
  @return null|\Zend\Http\PhpEnvironment\Response
  @throws \UnexpectedValueException