如何从JSON获取索引并将其放入HTML表?

时间:2019-01-12 12:49:43

标签: javascript jquery html json datatables

我有以下问题:

我有一个JS代码,用于获取JSON(可在某些URL上获取)并绘制表格。 JSON看起来像这样:

[{"price":12437,
  "quantity":4,
  "name":"\u0421\u0438\u0441\u0442\u0435\u043c\u043d\u044b\u0439 \u0431\u043b\u043e\u043a"},
 {"price":17043,
  "quantity":6,
  "name":"\u0412\u043e\u0434\u0430 \u0431\u0443\u0442\u0438\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0430\u044f"},         
 {"price":10594,
  "quantity":4,
  "name":"\u0428\u043a\u0430\u0444 \u043a\u043d\u0438\u0436\u043d\u044b\u0439"},
 {"price":17965,
  "quantity":7,
  "name":"\u0427\u0430\u0439\u043d\u0438\u043a \u044d\u043b\u0435\u043a\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u0438\u0439"},
 {"price":14280,
  "quantity":5,
  "name":"\u041b\u0430\u0437\u0435\u0440\u043d\u044b\u0439 \u043f\u0440\u0438\u043d\u0442\u0435\u0440"}]

代码在这里:live example。 我需要获取JSON中每个对象的索引,并将它们放入HTML表中(放入称为“ ID”的列中)。怎么做?预先谢谢你。

2 个答案:

答案 0 :(得分:1)

尝试使用function enu_explorer_shortcode() { $output = ''; include_once "eurno_include_file.php"; begin_eurno_explorer(); return $output; } add_shortcode( 'eurno_explorer', 'enu_explorer_shortcode' );

function enu_explorer_shortcode() {
ob_start();
include_once "eurno_include_file.php";
begin_eurno_explorer();
$eurno_explorer_output = ob_get_clean();
return $eurno_explorer_output;
}
add_shortcode( 'eurno_explorer', 'enu_explorer_shortcode' );

或查看fiddle我在所有功能中添加for的地方

此处:

for (var i = 0; i < your_array.length; i++){
    // log each from your array
    // where 'i' is the index that you try to find
    console.log(your_array[i]);

  }
}

和此处:

index

答案 1 :(得分:0)

我像20yco一样解决了这个问题:

 drawTable(data);
        function drawTable(data) {
            for (let i = 0; i < data.length; i++) {
                drawRow(i+1, data[i]);
            }
        }

        function drawRow(index, rowData) {
            let row = $("<tr class='table-data' />"),
                productSum = rowData.quantity * rowData.price;
            $(".products_table tbody").append(row);
            row.append($("<td>" + index + "</td>"));
            row.append($("<td>" + rowData.name + "</td>"));
            row.append($("<td>" + rowData.quantity + "</td>"));
            row.append($("<td>" + rowData.price + "</td>"));
            row.append($("<td>" + productSum + "</td>"));
        }

您可以在此处查看完整的表格:https://sashajarvi.github.io/products-table-json/table.html