Ajax请求数据无法显示到表中

时间:2018-09-05 10:50:29

标签: javascript jquery json ajax

JavaScript代码

$(function (){
  $.ajax({
    type : 'GET',
    url : 'order/orders.json',
    dataType : 'JSON',
    success: function(data) {
      /*var trHTML = '';
      $.each(orders, function (i, item) {
        trHTML += '<tr><th scope="row">' + orders.id[i] + '</th><td>' + orders.name[i] + '</td><td>' + orders.drink[i] + '</td></tr>';
      });
      $('#location').append(trHTML);*/
      alert('test');
    },  
    error: function (data) {
      alert(data.responseText);
    }
  });
}); 

orders.json

[
  {
    id: 1,
    name: 'john',
    drink: 'coffee'
  },
  {
    id: 2,
    name: 'doe',
    drink: 'tea'
  }
]

1 个答案:

答案 0 :(得分:0)

您应该首先使用索引获取对象,例如:

orders[i].id
orders[i].name
orders[i].drink

代替:

orders.id[i]
orders.name[i]
orders.drink[i]

完整代码为:

$(function (){
  $.ajax({
    type : 'GET',
    url : 'order/orders.json',
    dataType : 'JSON',
    success: function(orders) {
      var trHTML = '';
      $.each(orders, function(i, item) {
        trHTML += '<tr><th scope="row">' + orders[i].id + '</th><td>' + orders[i].name + '</td><td>' + orders[i].drink + '</td></tr>';
      });
      $('#location').append(trHTML);
    });
    },  
    error: function (data) {
      alert(data.responseText);
    }
  });
}); 

注意::确保success回调返回的响应参数名称为orders

获取实时示例:

$(function() {
  var orders = [{
      id: 1,
      name: 'john',
      drink: 'coffee'
    },
    {
      id: 2,
      name: 'doe',
      drink: 'tea'
    }
  ];
  var trHTML = '';
  $.each(orders, function(i, item) {
    trHTML += '<tr><th scope="row">' + orders[i].id + '</th><td>' + orders[i].name + '</td><td>' + orders[i].drink + '</td></tr>';
  });
  $('#location').append(trHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="location" border=1></table>