如何使用ajax检索JSON文件数据,当用户单击按钮时,内容显示在表中?

时间:2017-08-24 09:28:26

标签: javascript jquery json ajax

我正在尝试动态生成一个表,然后在我的网页中对该表的元素进行排序,但是从JSON文件中我无法检索数据 点击按钮生成表格。我能否知道我的代码在哪里出错。

// teamdetail.json file data:
{
  "teamList": [{
      "date": "24/07/2016",
      "venue": "Bengaluru",
      "matchdetails": "Qualifier 1 ? Gujarat Lions vs Royal Challengers Bangalore"
    }, {
      "date": "25/07/2016",
      "venue": "Delhi",
      "matchdetails": "Eliminator ? Sunrisers Hyderabad vs Kolkata Knight Riders"
    },
    {
      "date": "27/07/2016",
      "venue": "Bengaluru",
      "matchdetails": "Qualifier 2 ? Q1 Loser vs EL Winner"
    }
  ]
}
$(document).ready(function() {
  $("#getdetail").click(function() {
    $.getJSON('teamdetail.json', function(data) {
      var detail = '<tr><th colspan = 3>Playoff Team Schedule</th></tr>' +
        '<tr><th>Date</th><th>Venue</th><th>Match Details</th></tr>';
      $.each(data, function(key, value) {
        detail += '<tr>';
        detail += '<td>' + value.date + '</td>';
        detail += '<td>' + value.venue + '</td>';
        detail += '<td>' + value.matchdetails + '</td>';
        detail += '</tr>';
      });
      $('#teamdetail').append(detail);
    });
  });
});
<button type="button" id="getdetail">Get Team Details</button>
<table id="teamdetail"></table>

2 个答案:

答案 0 :(得分:1)

您的问题是因为您的JSON响应不是数组 - 它是一个具有属性const order = new Schema({ order_status: Number, foodtruck_id: { type: Schema.Types.ObjectId, ref: 'foodtruck' }, customer_id: { type: Schema.Types.ObjectId, ref: 'user' }, items: [{ type: Schema.Types.ObjectId, ref: 'items' }], user_type: Boolean, order_time: Date, order_rating: { type: Number, default: 5.0 }, order_issue_comments: String, order_special_instruction: String, order_total: Number, order_location: String, order_coupon_code: String, payment_id: { type: Schema.Types.ObjectId, ref: 'payment' }, order_meta: { type: Schema.Types.ObjectId, ref: 'order_sub_info'} }, { versionKey: false }, { minimize: false }); order.options.toJSON = { transform(zipRequestDocument, ret, options) { // eslint-disable-line no-unused-vars if (!ret.order_meta){ ret.order_meta = {}; } }, }; 的对象,它是您要循环的数组。

如果您将teamList替换为$.each(data, ...),它应该可以正常工作。

答案 1 :(得分:1)

你必须遍历数据['teamList']

$(document).ready(function() {
  $("#getdetail").click(function() {
    $.getJSON('teamdetail.json', function(data) {

      var detail = '<tr><th colspan = 3>Playoff Team Schedule</th></tr>' +
        '<tr><th>Date</th><th>Venue</th><th>Match Details</th></tr>';

      $.each(data['teamList'], function(key, value) {
        detail += '<tr>';
        detail += '<td>' + value.date + '</td>';
        detail += '<td>' + value.venue + '</td>';
        detail += '<td>' + value.matchdetails + '</td>';
        detail += '</tr>';
      });
      $('#teamdetail').append(detail);
    });
  });
});

我希望它能帮助你干杯!