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


Send JSON Data from Controller to View in Blade: Laravel 5.2

下面是返回国家/地区数据的类

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));

下面应该是控制器代码:

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

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

您需要在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