我找到了用于读取和填充csv文件的javascript代码,但是此代码使用“ input”方法。我一直在尝试将此方法更改为URL解析,但始终失败。感谢您的帮助
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(",");
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $tmpHTML = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $tmpHTML += '<p>' + $colNames[$b] + ':</p>' + '<p id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" />' + $csvData[$a][$colNames[$b]] + '</p>';
}
document.getElementById("fields").innerHTML = $tmpHTML;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
<input type="file" id="fileBox" />
<div id="dropdown"></div>
<div id="fields"></div>