Clean Ajax controller implementation in Zend Framework

后端 未结 4 703
独厮守ぢ
独厮守ぢ 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:52

    The content need only be switched when you're actually calling an ajax action. I think the Zend way is a good way. It is very flexible and easy to implement. In most cases, different Controllers will have a need for a couple of ajax actions. I don't see the need or the advantage of a pure ajax controller.

    Every controller can have something like this in the init():

    $ajaxContext = $this->_helper->getHelper('AjaxContext');
    $ajaxContext->addActionContext('some-toggle', 'html');
    $ajaxContext->addActionContext('some-other-ajax-thing', 'json');
    $ajaxContext->initContext();
    

    The action looks like every other action. The view script has just one var like:

    response; ?>
    

    ... and has to be called actionname.ajax.phtml.

    Then, if you're pushing additional actions on your action stack, you need to do that only for non-ajax requests like so:

    if (!$request->isXmlHttpRequest())
    {
        //push actions on stack
    }
    

    Additionally, you have to pass a format param along with the ajax post url like posturl/format/html or posturl/format/json.

提交回复
热议问题