简体   繁体   English

如何使用jquery从json数组中提取数据并将其附加到html表中?

[英]How to extract data from json array with jquery and append it in html table?

I want to extract data from Json array and append it with html table with jquery like 我想从Json数组中提取数据,并用jquery将它附加到html表中

  • idly 5 闲置5
  • dosa 20 多萨20

This is how my browser console prints what my server returned 这是我的浏览器控制台如何打印服务器返回的内容

    {hotelMitem: Array(5)}
    hotelMitem: Array(5)
    0: {hname: "idly", iprice: "5"}
    1: {hname: "dosa", iprice: "20"}
    2: {hname: "dosa", iprice: "20"}
    3: {hname: "dosa", iprice: "20"}
    4: {hname: "dosa", iprice: "20"}
    length: 5
    __proto__: Array(0)
    __proto__: Object

But when i try to iterate & print with jQuery 但是当我尝试使用jQuery进行迭代和打印时

    var _jsonString = "";
                for(var key in data){
                    _jsonString +="key "+key+" value "+data[key]+ '</br>';
                }
    $("#datatable").append(_jsonString)

HTML OUTPUT what i get HTML输出我得到了什么

key hotelMitem value [object Object],[object Object],[object Object],[object Object],[object Object]

You need to loop through data.hotelMitem , not data itself. 您需要遍历data.hotelMitem ,而不是data本身。 As the keys are static you can just access them directly without the additional inner loop. 由于键是静态的,因此您可以直接访问它们而无需其他内部循环。 You then need to build the actual HTML to populate the table with tr and td elements. 然后,您需要构建实际的HTML,以使用trtd元素填充表。 You can achieve that using map() , like this: 您可以使用map()实现此目的,如下所示:

 var data = { hotelMitem: [{ hname: "idly", iprice: "5" }, { hname: "dosa", iprice: "20" }, { hname: "dosa", iprice: "20" } // more items... ] }; var html = data.hotelMitem.map(function(obj) { return `<tr><td>${obj.hname}</td><td>${obj.iprice}</td></tr>`; }); $("#datatable").append(html) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="datatable"></table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM