尝试从JSON文件

时间:2018-01-31 18:05:46

标签: javascript jquery

前提:

我正在使用javascript,并且一直在尝试在浏览器上显示一个包含一组人的填充JSON文件。我已经设法通过ajax显示它,但现在我正在尝试使用jQuery执行相同的任务。

问题:

问题在于它一直说 customerdata[i] undefined,似乎无法弄清楚原因。

$(function() {
  console.log('Ready');

  let tbody = $("#customertable tbody");

  var customerdata = [];

  $.getJSON("MOCK_DATA.json", function(data) {
    customerdata.push(data);
  });

  for (var i = 0; i < 200; i++) {
    //Cell for name
    let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);

    //Cell for birthdate
    let mDate = moment(customerdata[i].birthdate);
    let formattedmDate = mDate.format('YYYY-MM-DD');
    let birthdateTD = $('<td>').text(formattedmDate);

    //Cell for Address 
    let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');

    //Cell for Credits
    let creditTD = $('<td>').text(customerdata[i].credits);


    let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);

    tbody.append(row);
  }
})

MOCK_DATA.json

的示例内容
[
  {"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0@discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
  {"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1@uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]

2 个答案:

答案 0 :(得分:0)

问题是数据已经是一个数组。

所以你应该使用:

customerdata = data;

除此之外,您要在pos 0中创建一个包含所有数据的数组

答案 1 :(得分:0)

首先,你将一个数组推入一个数组,这意味着你在迭代数据时比你想要的更深一些。

其次,$.getJSON是一个异步任务。它不完整,意味着jQuery尝试附加数据时没有填充customerdata

通过将getJSON链接到您的AJAX电话,您应该等待then在您追加之前解决。

$.getJSON("MOCK_DATA.json")
    .then(function(customerdata){



        for(var i = 0; i < 200; i++){
           //Cell for name
           let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);

            //Cell for birthdate
           let mDate = moment(customerdata[i].birthdate);
           let formattedmDate = mDate.format('YYYY-MM-DD'); 
           let birthdateTD = $('<td>').text(formattedmDate);

           //Cell for Address 
           let addressTD = $('<td>').html("City: " + 
           customerdata[i].city + '<br>' + "Email: " + 
           customerdata[i].email + '<br>' + '<a 
           href='+customerdata[i].website+'>Website</a>');

           //Cell for Credits
           let creditTD = $('<td>').text(customerdata[i].credits);


           let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);

         tbody.append(row);
      }

})

使用这种方法,您也不需要将customerdata定义为空数组。