如何将表头添加到包含Ajax数据的动态生成的表中?

时间:2015-10-19 07:22:15

标签: javascript json ajax

我正在尝试从JSON数据动态添加表头。 我还需要生成标题(th),以便不会手动完成。

我有一个非常基本的工作示例:我熟悉JQuery解决方案,但是,我想用JavaScript方法做到这一点:

一些JSON格式的数据:

var value = [{
    "City": "KABUL",
        "Continent": "ASIA",
        "Country": "AFGHANISTAN",
        "CountryAbbr": "AF",
        "CountryId": "102120"
}, {
    "City": "MARIEHAMN",
        "Continent": "EUROPE",
        "Country": "ALAND ISLANDS",
        "CountryAbbr": "AX",
        "CountryId": "102115"
}];

JavaScript的:

var out = "<table>";

for ( var i = 0; i < value.length; i++) {
    out += "<tr><td>" + value[i].Country +
        "</td><td>" + value[i].City +
        "</td><td>" + value[i].CountryAbbr +
        "</td></tr>";
}
out += "</table>";

document.getElementById("tableContainer").innerHTML = out;

HTML:

<div id="tableContainer"></div>

工作小提琴: dynamically generated table containing Ajax data

1 个答案:

答案 0 :(得分:0)

如果您正在谈论表格标题/标题,那么下面的代码对您有帮助:

var value = [{
    "City": "KABUL",
        "Continent": "ASIA",
        "Country": "AFGHANISTAN",
        "CountryAbbr": "AF",
        "CountryId": "102120"
}, {
    "City": "MARIEHAMN",
        "Continent": "EUROPE",
        "Country": "ALAND ISLANDS",
        "CountryAbbr": "AX",
        "CountryId": "102115"
}];

var out = "<table>";
out+="<tr><th>Country</th><th>City</th><th>Country Code</th></tr>";//TABLE HEADER/HEADING----------
for ( var i = 0; i < value.length; i++ ) {
    out += "<tr><td>" + value[i].Country +
        "</td><td>" + value[i].City +
        "</td><td>" + value[i].CountryAbbr +
        "</td></tr>";
}
out += "</table>";

document.getElementById("tableContainer").innerHTML = out;

Here is the snapshot of your jsfiddle