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\'
If you just have JSON in a variable and you want to send it to the browser with the proper content-type set in the header, all you need to do is this:
return Response::json($json);
assuming, obviously, that $json
contains your JSON.
Depending on the details of your situation it might make more sense to use views (rather than building your JSON by concatenating strings) but this is still an option if you use a view to build the string. Something approximately along these lines should work:
$json = View::make('some_view_template_that_makes_json') -> with ('some_variable', $some_variable)
return Response::json($json);
(Apologies if I missed some part of the question that requires a more manual approach! At least this should be useful to someone else coming here and wondering how to send JSON from Laravel with the right content-type set.)
Response::json() is not available anymore.
You can use response->json() instead.
use Illuminate\Contracts\Routing\ResponseFactory;
$foobar = ['foo' => 0, 'bar' => 'baz'];
return response()->json($foobar);
Gives:
{"foo":0,"bar":"baz"}
With the corresponding headers.
In Laravel 5.4 you can do this:
$contents = view('embedded')->with('foo', $foo);
return response($contents)->header('Content-Type', 'application/javascript');
BTW, there is no need to set the header in the view.
In Laravel 5.6:
return response()
->view('embedded', ['foo' => $foo])
->header('Content-Type', 'application/javascript');
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;
This worked for me
return Response::view($landing)->header('X-Frame-Options', 'DENY');