我有一個JSON文件名爲data.json:導入本地JSON文件轉換成HTML表
[{
"Group-of-Signals name" : "DPI_0",
"Group-of-Signals description" : "",
"Signal name" : "EUVPulseCount",
"Signal data type" : "SDT_STRING",
"Signal unit of measurement" : "M",
"Signal description" : "",
"Signal ID" : "-1",
"Signal index" : "0",
"id" : 0
}, {
"Group-of-Signals name" : "DPI_0",
"Group-of-Signals description" : "",
"Signal name" : "EUVState",
"Signal data type" : "SDT_STRING",
"Signal unit of measurement" : "",
"Signal description" : "",
"Signal ID" : "-1",
"Signal index" : "1",
"id" : 1
}, {
"Group-of-Signals name" : "DPI_0",
"Group-of-Signals description" : "",
"Signal name" : "Loop_Name",
"Signal data type" : "SDT_STRING",
"Signal unit of measurement" : "",
"Signal description" : "",
"Signal ID" : "-1",
"Signal index" : "2",
"id" : 2
}, {
"Group-of-Signals name" : "DPI_0",
"Group-of-Signals description" : "",
"Signal name" : "Project_Info",
"Signal data type" : "SDT_STRING",
"Signal unit of measurement" : "",
"Signal description" : "",
"Signal ID" : "-1",
"Signal index" : "3",
"id" : 3
}
]
而且我得到了這一塊的HTML代碼,現在的作品,但我想有代碼添加的頭文件並不告訴腳本編碼頭文件的內容。當這個工作,我可以縮短我的代碼,只需使用一個for循環和重複槽頭的列表:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="test.css"></link>
</head>
<body>
<div class="table">
<script>
$.getJSON('./data.json', function (data){
html = ''
$.each(data, function(key, value){
html += "<div class=\"row\"></div>";
html += "<div class=\"cell\">" + value["Group-of-Signals name"] + "</div>";
html += "<div class=\"cell\">" + value["Group-of-Signals description"] + "</div>";
html += "<div class=\"cell\">" + value["Signal name"] + "</div>";
html += "<div class=\"cell\">" + value["Signal data type"] + "</div>";
html += "<div class=\"cell\">" + value["Signal unit of measurement"] + "</div>";
html += "<div class=\"cell\">" + value["Signal description"] + "</div>";
html += "<div class=\"cell\">" + value["Signal ID"] + "</div>";
html += "<div class=\"cell\">" + value["Signal index"] + "</div>";
});
html += "</div>";
$(".table").append(html);
});
</script>
</div>
</body>
</html>
UPDATE: 隨着millerf的代碼,我設法獲取數據,但現在我仍然有申報鍵這樣的:
var headers = ["name", "description", "name", "data type", "unit of measurement", "description", "id", "index", "ID"]
$.getJSON('./data.json', function (data){
html = ''
for (i=0; i<headers.length; i++) {
html += "<div class=\"cell\">" + headers[i] + "</div>";
}
要小心,由於安全問題,Chrome和其他一些瀏覽器不會讓您在本地執行ajax。 –