包括一个外部JSON文件以与Bootstrap一起使用

时间:2019-02-19 23:51:08

标签: javascript php json

我有这段代码,我希望在我的<table class="table"> <thead class = 'text-primary'> <th class="text-center">Date</th> <th></th> </thead> <tbody> @foreach ($member->outstanding as $o) <tr> <td class="text-center">{{$o->roll_id}}</td> <td class="text-center"><a href="{{action('RollController@updateRoll', $o->id)}}" title="Paid" class="btn btn-success"><i class="material-icons">done</i></a></td> </tr> @endforeach </tbody> </table> 循环中包含一个外部JSON文件以便显示。

JSON如下所示:

foreach()

我有此代码:

"items":[{"title":"ONE","content":"Something-1"},
{"title":"TWO","content":"Something-2"},
{"title":"THREE","content":"Something-3"}]

2 个答案:

答案 0 :(得分:0)

您必须像下面一样更改JSON文件

{
  "items": [
    {
      "title": "ONE",
      "content": "Something-1"
    },
    {
      "title": "TWO",
      "content": "Something-2"
    },
    {
      "title": "THREE",
      "content": "Something-3"
    }
  ]
}

因此,现在您可以使用此方法访问items数组。

$.get('https://api.myjson.com/bins/v5ko2', function(result, status) {

    var data = result.items;

    // console.log(data);

    $.each(data, function(i, item) {

        console.log(item.title);

        // Now follow you append code here
        // $('.latestinfo').append("");

    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 1 :(得分:0)

您应该使用$.getJSON(jsonpath,callbackFn)方法发送回调函数,以便在提取JSON时可以在回调函数的data参数中访问JSON。

var data = 'doc.json';

$.getJSON(data, function(data) {
  data.items.forEach(function(item, index) {

    $('.latestinfo').append(
      '<div class="panel panel-default">' +
      '<div class="card-header top" role="tab" id="heading_' + index + '">' +
      '<h4 class="mb-0">' +
      '<a role="button" class=" btn btn-link " data-toggle="collapse" data-parent="#accordion" href="#collapse_' + index + '" aria-expanded="true" aria-controls="collapse_' + index + '">' +
      item.title +
      '</a>' +
      '</h4>' +
      '</div>' +
      '<div id="collapse_' + index + '" class="collapse " role="tabpanel" data-parent="#accordion" aria-labelledby="heading_' + index + '">' +
      '<div class="panel-body">' + // improves readability with the +, concatenates strings
      item.content +
      '</div>' +
      '</div>' +
      '</div>'
    );
  });
})