我正在開發Wordpress中的網頁。該網頁需要與所有縣的組合框。我有一個csv格式的數據集,所有這些縣都有10k行。 當用戶在下拉列表中選擇一個縣時,我只想要顯示在網頁中的所選縣數據。這是我的要求。Javascript將CSV文件加載到數組中
在WordPress,我的網頁,我將使用
<script type="text/javascript" src="http://xxx/wp content/uploads/2014/05/countyList1.js"></script>
和網頁下拉代碼的js文件是
<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>
在countyList1.js文件我有setCounties()和getSelectedCountyData()函數。
到目前爲止,我可以看到與縣列表的下拉列表。我不知道如何讀取CSV文件並將選定的縣過濾器應用到此列表。
我試過FileReader對象,我可以在網頁上加載CSV內容,但我不希望用戶選擇CSV。我已經有了這個數據集。
我想從這個SO後How to read data From *.CSV file using javascript?這個jquery.csv-0.71庫,但我需要幫助。
這裏是當一個縣被選定
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);
}
@Teemu刪除它後,我得到錯誤無法讀取未定義的屬性ajax。感謝您的幫助。 – Aqua267