简体   繁体   English

使用Javascript从REST API调用中创建带有数据的表

[英]Create a table with data from REST API call using Javascript

I need to create a table from JSON data that I get from a REST API. 我需要根据从REST API获得的JSON数据创建一个表。 The problem: for this specific app, I can't use Angular. 问题:对于这个特定的应用程序,我无法使用Angular。

My question is: do I have to use var table = document.createElement("TABLE"); 我的问题是:是否必须使用var table = document.createElement("TABLE"); in the script and create the whole table in the script? 在脚本中并在脚本中创建整个表? Or there's nicer / elegant way to separate the code and in the .html file to build the table? 还是有一种更好/更优雅的方法来分离代码,并在.html文件中构建表?

In other words, something that is more similar to the one way data binding in Angular. 换句话说,它与Angular中的单向数据绑定更相似。 So far I only used angular to work with REST API, but for this specific project I have to use Vanilla. 到目前为止,我仅使用angular来使用REST API,但是对于此特定项目,我必须使用Vanilla。

Thanks. 谢谢。

It's really easy to accomplish in vanilla JS, it just takes some lines - just keep appending elements and iterating. 在原始JS中,这确实很容易实现,只需要一行代码-只需不断追加元素并进行迭代即可。 For example 例如

 const input = [ { foo: 'f', bar: 'b' }, { foo: 'ff', bar: 'bb' }, { foo: 'fff', bar: 'bbb' }, { foo: 'f', bar: 'b' }, ]; const table = document.body.appendChild(document.createElement('table')); const thead = table.appendChild(document.createElement('thead')); const tr = thead.appendChild(document.createElement('tr')); const columnTexts = Object.keys(input[0]); columnTexts.forEach((columnText) => { tr.appendChild(document.createElement('td')) .textContent = columnText; }); const tbody = table.appendChild(document.createElement('tbody')); input.forEach((item) => { const tr = tbody.appendChild(document.createElement('tr')); const values = Object.values(item); values.forEach(value => { tr.appendChild(document.createElement('td')) .textContent = value; }); }); 

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

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