gpt4 book ai didi

javascript - 显式返回转义的 JSON 响应与仅在 Laravel/PHP 中返回数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:23:35 24 4
gpt4 key购买 nike

如果我比较 5.25.3 Laravel 的文档,5.3 文档似乎鼓励只返回一个包含数据的数组,该数组将自动转换为 JSON 响应(内容类型 "application/json")。我注意到从 Controller 返回一个数组,将返回未转义的 JSON。

return ['country_id' => $countryId, 'iso2' => 'EG', 'iso3' => 'EGY', 'country_name' => $countryName, 'name' => 'EGYPT', 'active' => 1, 'published' => 1];

返回

[{"country_id":63,"iso2":"EG","iso3":"EGY","country_name":"Egypt","name":"EGYPT","active":1,"published":1}]

但使用 json_encode() 将 PHP 数组显式转换为 JSON 字符串并将其作为响应返回,返回转义的 JSON。

return response()->json(json_encode(['country_id' => $countryId, 'iso2' => 'EG', 'iso3' => 'EGY', 'country_name' => $countryName, 'name' => 'EGYPT', 'active' => 1, 'published' => 1]));

返回

[{\"country_id\":63,\"iso2\":\"EG\",\"iso3\":\"EGY\",\"country_name\":\"Egypt\",\"name\":\"EGYPT\",\"active\":1,\"published\":1}]

是否有任何理由使用更详细的返回方式(我没有在客户端使用 eval,只有 JSON.parse() 将未转义和转义的 JSON 转换为相同的 javascript 对象)?

最佳答案

有两点:

  1. 根据文档 https://laravel.com/docs/5.3/responses#creating-responses

The framework will automatically convert the array into a JSON response

喜欢:

Route::get('/', function () {
return [1, 2, 3];
});
  1. 并根据https://laravel.com/docs/5.3/responses#json-responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array into JSON using the json_encode PHP function

喜欢:

return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);

你在这两个方面都是对的,但你正在获取转义代码,因为你使用了 json_encode() 两次,一次是因为 response()->json() 根据文档在内部使用该函数,另一个在该函数的代码中明确使用:response()->json(json_encode(...)),删除内部 json_encode 才能正常工作。

我已经测试了两种样式并且接收到的 header 是相同的,所以我考虑使用显式 response()->json() 与只返回一个数组作为偏好只要您使用实现该功能的版本。 5.2及以下好像没有。

关于javascript - 显式返回转义的 JSON 响应与仅在 Laravel/PHP 中返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com