我正在尝试输出动态javascript文件以包含来自具有[script src=""]
标记的外部网站。由于视图使用的是Blade引擎,因此它呈现为text/html
。
我希望此视图的Content-Type
标题设置为application/javascript
,以避免Chrome因“Resource interpreted as Script but transferred with MIME type text/html:
”等消息而烦恼我
我的控制器:
{
// ...
return View::make('embedded')->with('foo', $foo);
}
观点本身:
<?php
header('Content-Type: application/javascript; charset=UTF-8', true);
?>(function(jQuery) {
// append stylesheets to <head>
var file;
// ...
})(jQuery);
我发现我可以在我的视图中使用header()
按预期添加X-Content-Type
之类的自定义标头,但是当我尝试重新定义Content-Type
标头时,它似乎不会即使将replace
参数设置为true
,也可以执行任何操作。
我肯定在这里遗漏了一些明显的东西,非常感谢你指出我:)
非常感谢你的帮助
答案 0 :(得分:41)
Laravel允许您通过Response类修改标头信息,因此您必须使用它。从视图中删除header
行,并在控制器中尝试这样做:
$contents = View::make('embedded')->with('foo', $foo);
$response = Response::make($contents, $statusCode);
$response->header('Content-Type', 'application/javascript');
return $response;
答案 1 :(得分:7)
在Laravel 5.4中你可以这样做:
$contents = view('embedded')->with('foo', $foo);
return response($contents)->header('Content-Type', 'application/javascript');
顺便说一句,没有必要在视图中设置标题。
答案 2 :(得分:3)
如果您在变量中只有JSON并且想要将其发送到标题中设置了正确内容类型的浏览器,那么您需要做的就是:
return Response::json($json);
显然,假设$json
包含您的JSON。
根据您的情况的详细信息,使用视图可能更有意义(而不是通过连接字符串来构建JSON),但如果您使用视图来构建字符串,这仍然是一个选项。大致沿着这些线的东西应该起作用:
$json = View::make('some_view_template_that_makes_json') -> with ('some_variable', $some_variable)
return Response::json($json);
(道歉,如果我错过了需要更多手动方法的问题的某些部分!至少这对来到这里的其他人有用,并想知道如何使用正确的内容类型集从Laravel发送JSON。)
答案 3 :(得分:2)
Response :: json()不再可用。
您可以使用response-&gt; json()代替。
use Illuminate\Contracts\Routing\ResponseFactory;
$foobar = ['foo' => 0, 'bar' => 'baz'];
return response()->json($foobar);
给出:
{"foo":0,"bar":"baz"}
使用相应的标题。
答案 4 :(得分:2)
在Laravel 5.6中:
return response()
->view('embedded', ['foo' => $foo])
->header('Content-Type', 'application/javascript');
答案 5 :(得分:0)
这对我有用
return Response::view($landing)->header('X-Frame-Options', 'DENY');