从控制器发送 JSON 数据到 Blade 中查看:Laravel 5.2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36237131/
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
Send JSON Data from Controller to View in Blade: Laravel 5.2
提问by Pankaj
Below is the class that returns Country data
下面是返回国家数据的类
class CountryData {
public function GetCountries() {
return response()->json(['Data' => \App\Models\CountryModel::all()]);
}
}
I have following Json Data returned by above function
我有以下由上述函数返回的 Json 数据
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json
{
"Data":[
{
"CountryID" : 1,
"Country" : "United States",
"CountryCode": "US"
}
]
}
Below is the code in Controller.
下面是控制器中的代码。
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
Below is the code in View
下面是视图中的代码
@foreach($Countries["Data"] as $Country)
<tr class="odd pointer">
<td class=" ">{{$Country["Country"]}}</td>
<td class=" ">{{$Country["CountryCode"]}}</td>
</tr>
@endforeach
When I type echo $Countries;
I get above text. When I type echo json_decode($Countries, true);
It shows blank. Can you please guide me why this is happening?
当我打字时,echo $Countries;
我得到了上面的文字。当我输入echo json_decode($Countries, true);
它显示空白。你能指导我为什么会这样吗?
Reason I am doing this because data is being passed into Blade using below code.
我这样做的原因是因为使用以下代码将数据传递到 Blade 中。
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
采纳答案by Pankaj
Below should be the controller code:
下面应该是控制器代码:
return view('Country.List')->with('Countries', $Countries->getData()->Data);
^^^^^^^^^^^^^^^
But I am not sure if this is correct way to fix this issue. I am reading JsonResponse
.
但我不确定这是否是解决此问题的正确方法。我正在阅读JsonResponse
。
回答by Ajay
You need to add true in the json_decode($data,true) function. Change this
您需要在 json_decode($data,true) 函数中添加 true 。改变这个
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
Change to
改成
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries,true));
View
看法
@foreach($Countries["Data"] as $Country)
<tr class="odd pointer">
<td class=" ">{{$Country["Country"]}}</td>
<td class=" ">{{$Country["CountryCode"]}}</td>
</tr>
@endforeach