phalcon控制器方法返回json

骑驴找蚂蚁 · 2017年12月13日 · 阅读 1.3k

Base控制器实现afterExecuteRoute方法:

/**
     * @param Dispatcher $dispatcher
     */
    public function afterExecuteRoute(Dispatcher $dispatcher)
    {
        $return = $dispatcher->getReturnedValue();
        if ($this->request->isAjax() === true || is_array($return)) {
            $this->view->disableLevel(array(
                View::LEVEL_ACTION_VIEW => true,
                View::LEVEL_LAYOUT => true,
                View::LEVEL_MAIN_LAYOUT => true,
                View::LEVEL_AFTER_TEMPLATE => true,
                View::LEVEL_BEFORE_TEMPLATE => true
            ));
            $this->response->setContentType('application/json', 'UTF-8');
            $return['code'] = isset($return['code'])  ? $return['code'] : 1;
            $return['message'] = isset($return['message']) ? $return['message'] : '';
            $this->response->setJsonContent($return);
        }
        return $this->response->send();
    }

 

入口文件:

$di = require dirname(__DIR__) . '/bootstrap.php';
$application = new Phalcon\Mvc\Application($di);
try {
    /*
     * @var $response Response
     */
    $response = $application->handle();
    echo $response->getContent();
} catch (\Exception $e) {
    echo 'Exception: ', $e->getMessage();
}

关于作者

全栈工程师

文章被阅读 105.9k
获赞 11