JSONP 与 Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13747383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:26:38  来源:igfitidea点击:

JSONP with Laravel

phpjavascriptjqueryjsonplaravel

提问by Nyxynyx

Browser sends JSONP requets to Laravel, Laravel returns the results to browser. In the brower console, I get the warning:

浏览器向 Laravel 发送 JSONP 请求,Laravel 将结果返回给浏览器。在浏览器控制台中,我收到警告:

Resource interpreted as Script but transferred with MIME type text/html:

I believe this is due to improper headers in the JSONP response? How should this warning be fixed?

我相信这是由于 JSONP 响应中的标头不正确?应该如何修复此警告?

PHP

PHP

$callback = Input::get('callback');
$result = DB::table('users')->find(123);

return $callback . '(' . json_encode($result) . ')';

Response::JSON($result)will return the usual JSON response I believe, not the JSONP variant with the callback function name wrapping around the payload.

Response::JSON($result)我相信将返回通常的 JSON 响应,而不是带有回调函数名称的 JSONP 变体。

回答by Raul Duran

You can do this in Lavavel 4: (Original: Tu puedes hacer esto en Laravel 4)

你可以在 Lavavel 4 中做到这一点:(原文:Tu puedes hacer esto en Laravel 4)

Response::json($result)->setCallback(Input::get('callback'));

回答by Jesse O'Brien

You can provide the headers in the Response::json() call.

您可以在 Response::json() 调用中提供标头。

Response::json($result, 200, array('Content-Type' => 'application/javascript'));

The correct MIME type for JSONP is application/javascript.

JSONP 的正确 MIME 类型是 application/javascript。

回答by Prashant Barve

For Laravel(5.1 and above) or Lumen(5.1 and above):

对于 Laravel(5.1 及以上)或 Lumen(5.1 及以上):

if you would like to create a JSONP response, you may use the JSON method in addition to setCallback:

如果您想创建 JSONP 响应,除了 setCallback 之外,您还可以使用 JSON 方法:

return response()
    ->json(['name' => 'Abigail', 'state' => 'CA'])
    ->setCallback($request->input('callback'));

回答by JMHeap

Response::json($result)->setCallback(Input::get('callback'));

is better as suggested by Raul Duranas you don't have to manipulate the $result.

正如劳尔·杜兰( Raul Duran)所建议的那样更好,因为您不必操纵 $result。

The other option is echo instead of using the Response.

另一个选项是 echo 而不是使用响应。