Clean Ajax controller implementation in Zend Framework

后端 未结 4 705
独厮守ぢ
独厮守ぢ 2021-02-10 08:48

I need a controller in my Zend Framework project, which should handle only ajax requests.

My approach at the moment is to extend the Zend_Controller_Action:



        
4条回答
  •  攒了一身酷
    2021-02-10 09:44

    markus explained the most "Zend Like" way and his explanation is correct. But you see it as too much overhead because he missed to show you how much the "json context switch" is the best for your case.

    Look how short it is :

    //In your controller, activate json context for ANY called action in once
    
    public function init(){
        $action = $this->_getParam('action');
        $this->_helper->getHelper('contextSwitch')
             ->addActionContext($action, 'json')
             ->initContext();
    }
    

    And thats all, you don't need any view scripts, all the variables you assign via $this->view will be serialized into a JSON object.

    Oh and you don't want to add the context in the urls? Ok, just activate it by default in your route

    routes.ajax.route = '/ajax/:action/*'
    routes.ajax.defaults.controller = ajax
    routes.ajax.defaults.action = index
    routes.ajax.defaults.format = json
    

提交回复
热议问题