Zend Framework 2: Auto disable layout for ajax calls

前端 未结 8 1796
终归单人心
终归单人心 2020-12-16 13:26

An AJAX request to one of my controller actions currently returns the full page HTML.

I only want it to return the HTML (.phtml contents) for that particular action.

8条回答
  •  暖寄归人
    2020-12-16 13:51

    Here's the best solution (in my humble opinion). I've spent almost two days to figure it out. No one on the Internet posted about it so far I think.

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager= $e->getApplication()->getEventManager();
    
        // The next two lines are from the Zend Skeleton Application found on git
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    
        // Hybrid view for ajax calls (disable layout for xmlHttpRequests)
        $eventManager->getSharedManager()->attach('Zend\Mvc\Controller\AbstractController', MvcEvent::EVENT_DISPATCH, function(MvcEvent $event){
    
            /**
             * @var Request $request
             */
            $request = $event->getRequest();
            $viewModel = $event->getResult();
    
            if($request->isXmlHttpRequest()) {
                $viewModel->setTerminal(true);
            }
    
            return $viewModel;
        }, -95);
    
    }
    

    I'm still not satisfied though. I would create a plugin as a listener and configure it via configuration file instead of onBootstrap method. But I'll let this for the next time =P

提交回复
热议问题