我正在尝试使用jQuery
AJAX调用成功将数据从5行数据库(
MySQL)显示到表的行.数据采用JSON格式.
问题:我无法弄清楚所有这些行.我只能得到一行,但控制台显示了JSON格式的所有行.
$.ajax({ url: '<?PHP echo base_url('ads/select_post'); ?>',data: {},dataType: "json",cache: false,success: function (data) { $.each(data,function (i,val) { console.log(val.name); $("#name").html(val.name); $("#price").html(val.price); $("#addr").html(val.addr); $("#des").html(val.des); $("#viewed").html(val.viewed); $("#status").html(val.status); }); } });
控制台输出:
[{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status" :"1"},{"name":"Heng","addr":" dflkas;df","des":"asdfasdf","status":"1"},{"name":"asdDasdA","addr":"asdADasd","des":"ASDasdASD",{"name":"asdfas","addr":"fasdfas","des":"dfasdf","viewed" :"0",{"name":"asdf","addr":"asdfasdfas","des":"asdfasdfasdf","status":"1"}]
表的HTML我正在发送数据,
<tbody id="items"> <tr> <td>1</td> <td><a><div id="name"></div> </a></td> <td><a><div id="price"></div> </a></td> <td><a><div id"addr"></div></a></td> <td><div id="des"></div> </td> <td><a><div id="viewed"></div></a></td> <td><a><div id="status"></div></a></td> </tr>
请指教.
解决方法
很多好的答案,但由于我创建了一个例子,我也会发布.如果没有什么可以给你,或别人,替代解决方案.我正在使用类而不是Id,并保留原有的结构.
由于这被接受为答案,我还应该提到为什么你的代码失败:
您的每个循环都不断覆盖表行数据的内容,而不是创建新行.另一件需要修复的事情是,您已经给出了列Id,并且如果要重复这些行,则不能保留(因为它们),因为页面中的Id必须是唯一的.
创建新元素有很多方法.我选择了克隆(),因为我想,你总是会有一行头,可以很容易地用于克隆/复制.另外我添加了一个唯一的Id属性给每个tr.这些在下面的当前实现中并不真正使用,但是稍后在项目中可能会很好.
var data = [{"name":"dfasdfas","des":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfas","status":"1"}]; //place within the Ajax success $.each(data,function(i,val) { var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (i + 1)); currRow.find('td:eq(0)').html(i + 1); currRow.find('.name').html(val.name); currRow.find('.price').html(val.price); currRow.find('.addr').html(val.addr); currRow.find('.des').html(val.des); currRow.find('.viewed').html(val.viewed); currRow.find('.status').html(val.status); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody id="items"> <tr id="tr0"> <td>Id</td> <td><a><div class="name">Name</div></a></td> <td><a><div class="price">Price</div></a></td> <td><a><div class="addr">Addr</div></a></td> <td><div class="des">Des</div></td> <td><a><div class="viewed">Viewed</div></a></td> <td><a><div class="status">Status</div></a></td> </tr> </tbody> </table>