2016-01-20 57 views
1

我的JSON數組的格式,我試圖在一個HTML表,以顯示在locTable值顯示JSON Object值到表

"categoryName": [ 
"Construction", 
"Emergency Response", 
"Equipment", 
"General", 
"General Safety", 
"Marine", 
"Materials", 
"Products", 
"Protection of Workers", 
"Transport", 
"Workplace" 
], 
"locTable": [ 
{ 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
}, 
{ 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
}, 
{ 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
}, 

我的HTML代碼

<table class="red" style="width: 100%; height: 100%;"> 
<thead> 
<tr> 
<th>Category</th> 
<th class="right">Rele Completed</th> 
<th class="right">Eval Completed</th> 
</tr> 
</thead> 
<tbody id="display" class="no-border-x"> 
</tbody> 
</table> 

我試圖遍歷JSON的使用jQuery的對象,但我無法獲得正確的值顯示,我的代碼的結果顯示未定義。我試圖獲得結果的代碼。

var trHTML = ''; 
jQuery.each(json.locTable, function (k, item) {     
trHTML += '<tr><td>' + item.category + '</td><td>'  
+item.evaluationPercent + '</td><td>' +item.relevancePercent + 
'</td></tr>'; 
}); 
jQuery('#display').append(trHTML); 

回答

0

我不知道你是否沒有發佈你的整個JSON,但目前它是無效的。這是有效的:

var json = { 
    "categoryName": [ 
    "Construction", 
    "Emergency Response", 
    "Equipment", 
    "General", 
    "General Safety", 
    "Marine", 
    "Materials", 
    "Products", 
    "Protection of Workers", 
    "Transport", 
    "Workplace" 
    ], 
    "locTable": [{ 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
    }, { 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
    }, { 
    "evaluationPercent": 100, 
    "relevancePercent": 100, 
    "category": "Workplace", 
    "ldloc": [] 
    }] 
}; 

而且它的工作原理,請參閱:https://jsfiddle.net/ve7r4422/

0

var json = { 
 
    "locTable": [{ 
 
    "evaluationPercent": 80, 
 
    "relevancePercent": 100, 
 
    "category": "Workplace", 
 
    "ldloc": [] 
 
    }, { 
 
    "evaluationPercent": 90, 
 
    "relevancePercent": 70, 
 
    "category": "Workplace", 
 
    "ldloc": [] 
 
    }, { 
 
    "evaluationPercent": 100, 
 
    "relevancePercent": 40, 
 
    "category": "Workplace", 
 
    "ldloc": [] 
 
    }] 
 
}; 
 

 
jQuery('#display').append($.map(json.locTable, function(record){ 
 
    return '<tr><td>'+ record.category +'</td><td>'+ record.evaluationPercent +'</td><td>'+ record.relevancePercent +'</td></tr>'; 
 
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table class="red" style="width: 100%; height: 100%;"> 
 
    <thead> 
 
    <tr> 
 
     <th>Category</th> 
 
     <th class="right">Rele Completed</th> 
 
     <th class="right">Eval Completed</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody id="display" class="no-border-x"></tbody> 
 
</table>