Laravel JSON response without backslashes

﹥>﹥吖頭↗ 提交于 2021-01-19 04:28:11

问题


I am using AJAX post data to my controller.

PHP Code:

return response()->json($request->root() . '/summer-uploads/' . $store);

It returns:

"http:\/\/domain.test\/summer-uploads\/summer-uploads\/PGARvUyeXiAbbTOc90b6HGXXf9ZHmqehOA5f25pE.jpeg"

As you can see it's adding backslashes, some kind of escaping. How can i remove it, so it would be looking like this:

"http://domain.test/summer-uploads/summer-uploads/PGARvUyeXiAbbTOc90b6HGXXf9ZHmqehOA5f25pE.jpeg"


回答1:


The docs does not show all the arguments to the json method.

But they are tucked away in the source.

JsonResponse->__construct():

/**
 * Constructor.
 *
 * @param  mixed  $data
 * @param  int    $status
 * @param  array  $headers
 * @param  int    $options
 * @return void
 */
 public function __construct($data = null, $status = 200, $headers = [], $options = 0)
 {
     //...
 }

The options parameter would be the json_encode() parameters.

So for example, pretty print and unescaped slashes:

response()->json(..., 200, [], JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);



回答2:


try returning it inside a url

url('all your path concatenations')

in your case

return response()->json(url('/summer-uploads/' . $store));



回答3:


If you're using Eloquent: API Resources you may have a similar problem. The best way to apply json options to your Response or ResponseCollection is:

public function withResponse($request, $response)
{
    $response->setEncodingOptions(JSON_UNESCAPED_SLASHES);
}


来源:https://stackoverflow.com/questions/50998771/laravel-json-response-without-backslashes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!