Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

php - How to make Laravel return a View's "Content-Type" header as "application/javascript"?

I'm trying to output a dynamic javascript file for inclusion from external websites with the [script src=""] tag. As the view is using the Blade engine, it's rendered as text/html.

I'd like the Content-Type header to be set to application/javascript for this view only to avoid Chrome bugging me with messages like "Resource interpreted as Script but transferred with MIME type text/html:"

My controller:

{
    // ...
    return View::make('embedded')->with('foo', $foo);
}

The view itself:

<?php
header('Content-Type: application/javascript; charset=UTF-8', true);
?>(function(jQuery) {
    // append stylesheets to <head>
    var file;
    // ...
})(jQuery);

I've found that I can use header() in my view to add custom headers like X-Content-Type as expected, however when I try to redefine the Content-Type header it doesn't seem to do anything even with the replace parameter set as true.

I'm surely missing something obvious here, would appreciate your pointing it out to me :)

Thanks a lot for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Laravel lets you modify header information via the Response class, so you have to make use of it. Remove the header line from your view and try it like this in your controller:

$contents = View::make('embedded')->with('foo', $foo);
$response = Response::make($contents, $statusCode);
$response->header('Content-Type', 'application/javascript');
return $response;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...