Zend Framework 2: Auto disable layout for ajax calls

前端 未结 8 1810
终归单人心
终归单人心 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 14:04

    I think the problem is that you're calling setTerminal() on the view model $e->getViewModel() that is responsible for rendering the layout, not the action. You'll have to create a new view model, call setTerminal(true), and return it. I use a dedicated ajax controller so there's no need of determining whether the action is ajax or not:

    use Zend\View\Model\ViewModel;
    use Zend\Mvc\MvcEvent;
    use Zend\Mvc\Controller\AbstractActionController;
    
    class AjaxController extends AbstractActionController
    {
        protected $viewModel;
    
        public function onDispatch(MvcEvent $mvcEvent)
        {
            $this->viewModel = new ViewModel; // Don't use $mvcEvent->getViewModel()!
            $this->viewModel->setTemplate('ajax/response');
            $this->viewModel->setTerminal(true); // Layout won't be rendered
    
            return parent::onDispatch($mvcEvent);
        }
    
        public function someAjaxAction()
        {
            $this->viewModel->setVariable('response', 'success');
    
            return $this->viewModel;
        }
    }
    

    and in ajax/response.phtml simply the following:

    response ?>
    

提交回复
热议问题