在Blade视图中从控制器发送JSON数据:Laravel 5.2

3
以下是返回国家数据的类:
class CountryData {
    public function GetCountries() {
        return response()->json(['Data' => \App\Models\CountryModel::all()]);
    }
}

我通过上述函数返回了以下Json数据

HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json 
{
    "Data":[
              {
                  "CountryID"  : 1,
                  "Country"    : "United States",
                  "CountryCode": "US"
              }
           ]
}

以下是控制器中的代码。

$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));

以下是视图中的代码:
@foreach($Countries["Data"] as $Country)
    <tr class="odd pointer">
        <td class=" ">{{$Country["Country"]}}</td>
        <td class=" ">{{$Country["CountryCode"]}}</td>
    </tr>
@endforeach

当我输入echo $Countries;时,我得到上面的文本。当我输入echo json_decode($Countries, true);时,它显示为空白。你能指导我为什么会出现这种情况吗?
我这样做的原因是使用以下代码将数据传递到 Blade:
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));

那么,你究竟想要实现什么? - Alexey Mezenin
我想读取Json数据以在Blade中显示记录列表。 - Pankaj
2个回答

1
下面应该是控制器代码:

return view('Country.List')->with('Countries', $Countries->getData()->Data);
                                                           ^^^^^^^^^^^^^^^

但我不确定这是否是解决此问题的正确方法。我正在阅读JsonResponse

0
你需要在json_decode($data,true)函数中添加true。 将其更改为:
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));

更改为

$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries,true));

视图

@foreach($Countries["Data"] as $Country)
    <tr class="odd pointer">
        <td class=" ">{{$Country["Country"]}}</td>
        <td class=" ">{{$Country["CountryCode"]}}</td>
    </tr>
@endforeach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接