使用 Ajax 时如何停止渲染 Phalcon 模板?

How to stop rendering Phalcon template when Ajax is used?

我在我的 Phalcon 项目中使用了很多 Ajax,每个请求都由特定的 Controller/Action 处理,我禁用了模板渲染 (仅呈现视图)。

如果使用 Ajax 进行调用,如何全局禁用模板?

我找到了答案:)

abstract class ControllerBase extends Controller
{
    /**
     * Called in each Controller/Action request
     */
    public function initialize(){
        if($this->request->isAjax()){
            $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
        }

    ...

对于特定操作,您可以使用以下任一实现:

public function saveAction()
{
    $this->view->disable();

    // Operations go here.....

    $this->view->pick('some/view/to/display');
}

public function resetAction()
{
    $this->view->disable();

    // Operations go here.....

    echo 'reset action'
}

public function cancelAction()
{
    $this->view->disable();

    // Operations go here.....
    $response = new \Phalcon\Http\Response();
    $response->setStatusCode(200, 'OK');
    $response->setContentType('application/json', 'UTF-8');
    $response->setJsonContent('some content goes here', JSON_UNESCAPED_SLASHES);

    return $response->send();
}

可用的渲染级别是:

Class Constant          Description Order
LEVEL_NO_RENDER         Indicates to avoid generating any kind of presentation.  
LEVEL_ACTION_VIEW       Generates the presentation to the view associated to the action.    1
LEVEL_BEFORE_TEMPLATE   Generates presentation templates prior to the controller layout.    2
LEVEL_LAYOUT            Generates the presentation to the controller layout.    3
LEVEL_AFTER_TEMPLATE    Generates the presentation to the templates after the controller layout.    4
LEVEL_MAIN_LAYOUT       Generates the presentation to the main layout. File views/index.phtml   5

有关详细信息,请参阅:control-rendering-levels