通过ajax将数据附加到表中

我在将数据附加到表体时遇到问题。


代码

$.ajax({

  type:'GET',

  url:'{{url('dashboard/customer-groups')}}/'+ordID,

  success:function(data){

    console.log(data);  //screenshot below

  }

});

截屏

上面的 ajax 代码返回的数据分为 2 个类别(组和客户)

http://img1.mukewang.com/61e93eea0001702b05570259.jpg

HTML

<table id="data-table" class="table table-striped table-bordered">

    <thead>

    <tr>

        <th>#</th>

        <th>Name</th> // from customers array

        <th>Company</th> // from customers array

        <th>Province</th> // from customers array

        <th>City</th> // from customers array

        <th>Email</th> // from customers array

        <th>Industry</th> // from customers array

        <th>Group</th> // from group

    </tr>

    </thead>

    <tbody id="table_customer"></tbody>

</table>

任何的想法?


哔哔one
浏览 282回答 2
2回答

慕沐林林

.each()您可以使用on success遍历响应数据并将它们附加到表主体中。演示:let&nbsp; data = {customers: [&nbsp; {id: 1, name:'John', group_id: 111, industry_id: 'xyz', company: 'abc', province: 'aaa', city: 'vv', email: 'aa@gmail.com'},&nbsp; {id: 2, name:'Kate', group_id: 222, industry_id: 'lmn', company: 'abc2', province: 'bbb', city: 'qq', email: 'zz@gmail.com'}]};$(data.customers).each(function(_, i){&nbsp; var row = `<tr><td></td><td>${i.name}</td><td>${i.company}</td><td>${i.province}</td><td>${i.city}</td><td>${i.email}</td><td>${i.industry_id}</td><td>${i.group_id}</td></tr>`;&nbsp; $('#table_customer').append(row);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table id="data-table" class="table table-striped table-bordered">&nbsp; &nbsp; <thead>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>#</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Name</th>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <th>Company</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Province</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>City</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Email</th>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <th>Industry</th>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <th>Group</th>&nbsp;&nbsp; &nbsp; </tr>&nbsp; &nbsp; </thead>&nbsp; &nbsp; <tbody id="table_customer"></tbody></table>

慕森王

&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; type:'GET',&nbsp; &nbsp; &nbsp; url:'{{url('dashboard/customer-groups')}}/'+ordID,&nbsp; &nbsp; &nbsp; success:function(data){&nbsp; &nbsp; &nbsp; &nbsp; const tr = $('tr');&nbsp; &nbsp; &nbsp; &nbsp; for (var key in data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var obj = data[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var id = "<td>"+obj.id+"</td>";var group_id = "<td>"+obj.group_id+"</td>";&nbsp; &nbsp; &nbsp;// add more columns for other attributes&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var allTds = id+group_id;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; tr.append(allTds);&nbsp; &nbsp; &nbsp; &nbsp;$('#data-table').append(tr);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript