骑驴找蚂蚁

全干工程师

phalcon控制器方法返回json

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();
}

留言