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

前端 未结 6 1293
-上瘾入骨i
-上瘾入骨i 2020-12-14 08:41

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\'

相关标签:
6条回答
  • 2020-12-14 08:59

    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.)

    0 讨论(0)
  • 2020-12-14 09:06

    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.

    0 讨论(0)
  • 2020-12-14 09:10

    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.

    0 讨论(0)
  • 2020-12-14 09:17

    In Laravel 5.6:

    return response()
        ->view('embedded', ['foo' => $foo])
        ->header('Content-Type', 'application/javascript');
    
    0 讨论(0)
  • 2020-12-14 09:19

    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;
    
    0 讨论(0)
  • 2020-12-14 09:21

    This worked for me return Response::view($landing)->header('X-Frame-Options', 'DENY');

    0 讨论(0)
提交回复
热议问题