繁体   English   中英

以 HTML 格式显示来自 API 的 JSON 数据

[英]Displaying JSON Data from API in HTML

我有一个带有属性名称的对象数组,然后是两个数组(NCMovies 和 KRMovies)。 我想在 HTML 上显示这些数据,然后使用 CSS 对其进行样式设置。 JSON.stringify 数据的示例如下。 我试过 appendChild 和 appendNode ,但它不起作用。

JavaScript:

document.getElementById("answer").innerHTML = JSON.stringify(answer)

在屏幕上显示:

[{"name":"Laurence Fishburne","NCMovies":["Running with the Devil"],"KRMovies":["The Matrix Revolutions","The Matrix Reloaded","The Matrix"]}

您可以使用 JQuery 以更简单的方式处理它。

 var arrObject = [{"name":"Laurence Fishburne","NCMovies":["Running with the Devil"],"KRMovies":["The Matrix Revolutions","The Matrix Reloaded","The Matrix"]},{"name":"Laurence Fishburne 2","NCMovies":["Running with the Devil 2"],"KRMovies":["The Matrix Revolutions 2","The Matrix Reloaded 2","The Matrix 2"]}]; var ul = $("<ul>"); $.each(arrObject,function(){ var obj = this; ul.append($("<li>").text(obj.name)); var _ul1 = $("<ul>"); $.each(obj.NCMovies,function(){ _ul1.append($("<li>").text(this)); }); ul.append(_ul1); var _ul1 = $("<ul>"); $.each(obj.KRMovies,function(){ _ul1.append($("<li>").text(this)); }); ul.append(_ul1); }); $("#result").html(ul);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <div id="result"></div>

这是 vanilla javascript 中的最终代码:

 var data=[{"name":"Laurence Fishburne","NCMovies":["Running with the Devil"],"KRMovies":["The Matrix Revolutions","The Matrix Reloaded","The Matrix"]}]; function mapper(item){ var container=document.createElement('div'); var title=document.createElement('h1'); title.innerText=item.name; container.appendChild(title); var ncMovies=document.createElement('h2'); ncMovies.innerText="NCMovies"; container.appendChild(ncMovies); var ul1=document.createElement('ul'); item.NCMovies.forEach(function(it){ var li= document.createElement('li'); li.innerText=it; ul1.appendChild(li); }); container.appendChild(ul1); var krMovies=document.createElement('h2'); krMovies.innerText="KRMovies"; container.appendChild(krMovies); var ul2=document.createElement('ul'); item.KRMovies.forEach(function(it){ var li= document.createElement('li'); li.innerText=it; ul2.appendChild(li); }); container.appendChild(ul2); return container; } var elements=data.map(mapper); var body=document.querySelector('body'); elements.forEach(function(element){ body.appendChild(element); })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM