A
A
Albert Tobacco2015-04-23 10:12:51
Yii
Albert Tobacco, 2015-04-23 10:12:51

How to make respond with Content-Type "application/javascript" in Yii 2?

I do something like this

$headers = Yii::$app->response->headers;
        $headers->add('Content-Type', 'application/javascript');
        return "console.log('hello');";

but in the header comes
Content-Type:text/html; charset=UTF-8

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Makarov, 2015-04-24
@bighoc

Also, you can do it like this:
https://github.com/samdark/yii2-cookbook/blob/mast...

Z
zhdanovartur, 2016-02-06
@zhdanovartur

On the example of sitemap.xml where the wrapper in is not needed <response/>:

public function actionSitemap()
{
    $response = Yii::$app->response;
    $response->format = Response::FORMAT_RAW;
    $response->getHeaders()->set('Content-Type', 'application/xml; charset=utf-8');

    return $this->render('sitemap');
}

A
Alexander, 2015-04-23
@bIbI4k0

Use the set() method instead of add() because
www.yiiframework.com/doc-2.0/yii-web-headercollect... ()-detail

If there is already a header with the same name, the new one will be appended to it instead of replacing it.

A
Anton_Gorodezkiy, 2015-05-19
@Anton_Gorodezkiy

This is how I got it. Instead of the result of calling render, you return an array directly:

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return [
      'isError' => false,
      'message' => $message,
      'data' => $data
    ];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question