Reputation: 171
What I have: a csv (can be converted to xml or maybe to json) file that has many rows, each row contains several columns that store data about some profile.
What I need to do: to generate an html page that corresponds to each row automatically given the html elements' layout. Since I may have hundreds of rows and all pages got identical html elements (I mean, like an imdb or facebook profile) except the unique profile data shown to users, a small change to the layout of a page later would require days of stupid manual work.
Is there some kind of framework that can do what I seek to do? Thank you!
Upvotes: 1
Views: 2149
Reputation: 47101
You need three steps :
1) Use Ajax to fetch data from your server and turn it into an array. You could do this eg. with the following jQuery :
$.ajax({
type: "GET",
url: "data.csv",
success: CSVToHTMLTable
});
2) Once you have get your file, you need to parse it. Json and XML support are native in JavaScript. An easy & reliable way to do it for a CSV file, would be to use a library like Papa Parse :
var data = Papa.parse(data).data;
3) You need to define a function to transform your array into an HTML table. Here's how you could do this with jQuery :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
Here's how you can put everything together :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://localhost/test/data.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
Upvotes: 3