簡體   English   中英

使用JavaScript發布JSON數據到HTML

[英]Publishing JSON data to HTML using JavaScript

我排除了這樣的 outlook:與 output 有關的圖像

我想知道的是如何創建這個 output 而不必一次又一次地使用純 JavaScript 和 JSON 編寫<p> ,沒有任何 JS 庫。

JSON 數據如下所示:

[{"id":1,"first_name":"David","food":"Pizza","age":"24"},
{"id":2,"first_name":"Jack","food":"Hamburger","age":"22"},
{"id":3,"first_name":"Harrison","food":"Sweets","age":"8"},.....

我的 HTML 身體是這樣的

<body>
</div class="content">
<center>
<p><B>People and their Foods</B></p>
</center>
</div>
</body>

請幫助我,因為我是這個代碼世界的新手。

您可以遍歷數據並在每次迭代時動態創建元素並將它們分配給主/根 div。

 // javascript // pure javascript // function to render data function renderData (data) { var root = document.getElementById("root"); for(var i =0; i<data.length; i++){ // here you can also create inner loop as well. but following is easier for you. var div = document.createElement("div"); var para1 = document.createElement("P"); para1.innerText = "name:" + data[i].first_name; div.appendChild(para1); var para2 = document.createElement("P"); para2.innerText = "food:" + data[i].food; div.appendChild(para2); var para3 = document.createElement("P"); para3.innerText = "age:" + data[i].age; div.appendChild(para3); root.appendChild(div); } } // load your json data and then call renderData function var httpRequest = new XMLHttpRequest(); // asynchronous request httpRequest.open("GET", "local/path/file.json", true); httpRequest.send(); httpRequest.addEventListener("readystatechange", function() { if (this.readyState === this.DONE) { // when the request has completed var object = JSON.parse(this.response); // assuming that in json file data is an attribute renderData(object.data); } });
 <!-- html part --> <body> <div class="content"> <center> <p><b>People and their Foods</b></p> </center> <!-- == i have added one div with id root == --> <div id="root"></div> </div> </body>

嘗試如下代碼片段:

 const json = [{"id":1,"first_name":"David","food":"Pizza","age":"24"}, {"id":2,"first_name":"Jack","food":"Hamburger","age":"22"}, {"id":3,"first_name":"Harrison","food":"Sweets","age":"8"},] const content = document.querySelector('.content') json.forEach(j => { let div = document.createElement('div') div.id = j.id div.style = "margin-bottom: 2em;" content.appendChild(div) const divid = content.querySelector(`#${CSS.escape(j.id)}`) for(let key in j) { if(key !== 'id') { let p = document.createElement('p') let title = '' key === 'first_name' ? title = 'name' : title = key p.innerText = title.charAt(0).toUpperCase() + title.slice(1) + ': ' + j[key] divid.appendChild(p) } } })
 <body> <div class="content"> <h3>People and their Foods</h3> </div> </body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM