Zend Framework 2: Auto disable layout for ajax calls

前端 未结 8 1766
终归单人心
终归单人心 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:06

    I replied to this question and seems it maybe similar - Access ViewModel variables on dispatch event

    Attach an event callback to the dispatch event trigger. Once this event triggers it should allow you to obtain the result of the action method by calling $e->getResult(). In the case of an action returning a ViewModel it should allow you to do the setTerminal() modification.

    0 讨论(0)
  • 2020-12-16 14:07

    I had this problem before and here is a quikc trick to solved that.

    First of all, create an empty layout in your layout folder module/YourModule/view/layout/empty.phtml

    You should only echo the view content in this layout this way <?php echo $this->content; ?>

    Now In your Module.php set the controller layout to layout/empty for ajax request

    namespace YourModule;
    use Zend\Mvc\MvcEvent;
    
    class Module {
        public function onBootstrap(MvcEvent $e) {
            $sharedEvents = $e->getApplication()->getEventManager()->getSharedManager();
            $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
                if ($e->getRequest()->isXmlHttpRequest()) {
                    $controller = $e->getTarget();
                    $controller->layout('layout/empty');
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题