“An error occurred while handling another error: yii\web\HeadersAlreadySentException”

后端 未结 2 1856
孤独总比滥情好
孤独总比滥情好 2020-12-17 15:22

I am trying to submit a comment on a guestbook application based on the Yii 2 Framework. On localhost on my PC works everything fine, but on the shared hosting when I want t

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 16:19

    Since Yii 2.0.14 you cannot echo in a controller. A response must be returned:

    public function actionAdd_comment() {
        $model = new \app\models\Comments();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->comment_date = date('Y-m-d H:i:s');
            if ($model->save()) {
                return 'Thanks for your comment.';
            } else {
                return 'Failed!';
            }
        }
    }
    

    You may also call exit at the end of your method to prevent further processing or wrap your code with ob_start() and ob_get_clean(), if you're not able to avoid echo.

    public function actionAdd_comment() {
        $model = new \app\models\Comments();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $this->someMagicWithEcho();
            exit;
        }
    }
    

    or

    public function actionAdd_comment() {
        $model = new \app\models\Comments();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            ob_start();
            $this->someMagicWithEcho();
            return ob_get_clean();
        }
    }
    

提交回复
热议问题