我正在尝试将本地csv文件加载到html表。当我在chrome中加载html文件时,我无法查看内容。控制台说“导航到file:/// D:/report.html” 。没有错误信息。
$(document).ready(function() {
$.ajax({
type: "GET",
url: "file:///D:/results.csv",
success: function(data) {
processData(data);
}
});
});
function processData(allText) {
var record_num = 2;
var allTextLines = allText.split(/\r\n|\n/);
var entries = allTextLines[0].split(',');
var lines = [];
var headings = entries.splice(0, record_num);
while (entries.length > 0) {
var tarr = [];
for (var j = 0; j < record_num; j++) {
tarr.push(headings[j] + ":" + entries.shift());
}
lines.push(tarr);
}
var output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>" +
lines[i].slice(0, -1).split(",").join("</td><td>") +
"</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
}
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
align-content: center;
}
td {
border: 1px black solid;
padding: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id='container'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</body>
</html>
我找不到我犯错误的地方。 提前谢谢。
答案 0 :(得分:0)
这是正确的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "./results.csv",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var lines = [];
var tarr = [];
var val;
var record_num = 2;
var allTextLines = allText.split(/\r\n|\n/);
for (var k = 0;k < allTextLines.length-1;k++){
var entries = allTextLines[k].split(',');
var headings = entries.splice(0,record_num);
while (headings.length>0) {
for (var j=0; j<record_num; j++) {
val = headings.shift();
tarr.push(val);
}
}
}
var output = [],
i;
for (i = 0; i < tarr.length-1; i++){
output.push("<tr><td>"+ tarr[i].replace('"',"").slice(0,-1) + "</td><td>"+ tarr[i+1].replace('"',"").slice(0,-1) //my requirement is two columns
+ "</td></tr>");
i++;
}
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
}
</script>
</body>