2013-07-21 24 views
0

我试图将json响应显示到html表格中。其中一个字段是我想要在表格中显示的图像。我现在的代码只显示了json响应中的最后一个键/值,而不是表中的全部。如何显示通过从文件中读取的多行循环的html表格

<html> 
<head> 
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> 
<link rel="stylesheet" type="text/css" href="http://www.tutorialspoint.com/scripts/style.css" /> 
<script type="application/javascript"> 
function loadJSON() 
{ 
    var http_request = new XMLHttpRequest(); 
    var data_file = "/vcaWS/api/sources"; 

    http_request.onreadystatechange = function(){ 
     if (http_request.readyState == 4 ) 
     { 
     // Javascript function JSON.parse to parse JSON data 
     var jsonObj = JSON.parse(http_request.responseText); 

     for(var i=0;i<jsonObj.length;i++){ 
      document.getElementById("title").innerHTML = jsonObj[i].title; 
      document.getElementById("logo_sm").innerHTML = jsonObj[i].logo_sm; 
     } 
    } 
    } 
    http_request.open("GET", data_file, true); 
    http_request.send(); 
} 
</script> 
<title>Test JSON</title> 
</head> 
<body style="width:960px"> 
<h1>Test JSON</h1> 
<table class="src"> 
<tr><th>Title</th><th>Logo_Small</th></tr> 
<tr> 
<td><div id="title">Youtube</div></td> 
<td><div id="logo_sm">Youtube</div></td> 
</tr> 
</table> 
<div class="central"> 
<button type="button" onclick="loadJSON();">JSON Store </button> 
</body> 
</html> 

JSON响应是如下:

[ 
    { 
     "title":"Virtual Magician s Video Podcast", 
     "logo_sm":"http://a5.mzstatic.com/us/r30/Podcasts/v4/cf/53/e1/cf53e162-f4c7-7842-173d-7f7f2a79fd7e/mza_854261567010408552.100x100-75.jpg" 
    }, 
    { 
     "title":"shralp! //surfing video podcast//", 
     "logo_sm":"http://a5.mzstatic.com/us/r30/Podcasts/v4/ea/ff/d0/eaffd0d3-b1f9-e886-2ffd-5ff14bcb5edb/mza_1030973830906343038.100x100-75.jpg" 
    }, 
    { 
     "title":"this WEEK in TECH Video (small)", 
     "logo_sm":"http://a4.mzstatic.com/us/r30/Podcasts2/v4/fb/59/fc/fb59fc2d-b1a2-98cf-e1f8-32bae7217912/mza_5512264877031055372.100x100-75.jpg" 
    } 
] 

而且,我希望能显示JPG文件作为图像。目前,它的一个文本值显示在html表格中。

+0

是否要添加到表中或完全替换表内容? – Barmar

+0

我想将它添加到表格中。基本上,试图以标题Logo_sm的格式在 – user2602727

+0

之下具有3行格式将会有4行:原始HTML中的1行以及JSON中的3行。看到我的答案。 – Barmar

回答

0

您正在遍历JSON对象,但是在每次迭代中,您将用ith对象替换行的innerHTML。
因此它只会显示JSON对象的最后一项。
只需获取表格并为每个项目插入一行即可。

var mytable = document.getElementById("tableid"); 
for(var i=0;i<jsonObj.length;i++){ 

    var myrow = mytable.insertRow(0); 
    var mytitlecell = myrow.insertCell(0); 
    var mylogocell = myrow.insertCell(1); 
    mytitlecell.innerHTML = jsonObj[i].title; 
    mylogocell.innerHTML = "<img src='"+jsonObj[i].logo_sm+"'/>"; 
} 
1

这会将JSON数据添加为表中的新行。

var rows = ''; 
for(var i=0;i<jsonObj.length;i++){ 
    rows += '<tr><td class="title">' + jsonObj[i].title + '</td><td class="logo_sm">' + jsonObj[i].logo_sm + '</td></tr>'; 
} 
document.getElementsByTagName('table')[0].innerHTML += rows; 
+0

谢谢...它nows获取数据按预期...我可以显示logo_sm这是一个图像的链接,直接在表中显示该图像? – user2602727

+0

你可以做任何可以用HTML表示的东西。 – Barmar

相关问题