我正在 WordPress 中开发一个网页。该网页需要有一个包含所有县的组合框。我有一个 csv 格式的数据集,其中包含所有这些县的约 10k 行。
当用户在下拉列表中选择一个县时,我只想在网页中显示所选县的数据。这是我的要求。
在 WordPress,我的网页中,我使用添加 js 文件
<script type="text/javascript" src="http://xxx/wp content/uploads/2014/05/countyList1.js"></script>
网页下拉列表的代码是
<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>
在 CountyList1.js 文件中,我有 setCounties() 和 getSelectedCountyData() 函数。
到目前为止,我可以看到带有县列表的下拉列表。我不知道如何读取 CSV 文件并将选定的县过滤器应用到此列表。
我尝试了 FileReader 对象,我可以在网页上加载 CSV 内容,但我不希望用户选择 CSV。我已经有了数据集。
我正在尝试使用此 SO 帖子中的 jquery.csv-0.71 库如何使用 javascript 从 *.CSV 文件读取数据? https://stackoverflow.com/questions/7431268/how-read-data-from-csv-file-using-javascript/12289296#12289296但我需要帮助。
这是选择县时调用的代码
function getSelectedCountyData() {
cntrySel = document.getElementById('county');
//selCty = countyList[cntrySel.value];
handleFiles();
}
function handleFiles() {
$(document).ready(function () {
$.ajax({
type: "GET",
url: "D:\Docs\Desktop\csvfile.csv",
dataType: "csv",
success: function (data) { processData(data); }
});
});
}
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
console.log(lines);
drawOutput(lines);
}
function drawOutput(lines) {
//Clear previous data
document.getElementById("output").innerHTML = "";
var table = document.createElement("table");
for (var i = 0; i < lines.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < lines[i].length; j++) {
var firstNameCell = row.insertCell(-1);
firstNameCell.appendChild(document.createTextNode(lines[i][j]));
}
}
document.getElementById("output").appendChild(table);
}