[英]How to save a csv file uploaded from my machine into a data object in javascript?
我正在構建一個頁面,可以顯示來自 csv 文件的傳感器數據圖表。 用戶應該能夠單擊按鈕從他的機器中選擇所需的 csv 文件以顯示在圖表上。 為此,我正在使用 Highcharts 庫。 該圖表按需要工作,但我只能在代碼中輸入 csv 文件。 當我上傳文件並更新時,什么也沒有發生。 那么如何使“data.csv”動態化呢? 我的想法是以某種方式將其保存到全局數據 object 中,然后可以將其傳遞到 ajax url 中。 我不知道如何實現,因為這是我的第一個 javascript 項目。
<!DOCTYPE html> <!-- Write your comments here -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.highcharts.com/highcharts.js"></script> <!-- library include-->
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<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>
<title>Airmeter</title>
</head>
<body>
<div id="container"></div>
<form id='form'>
<input type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" id="input" />
<button type='submit'>
update the chart
</button>
</form>
<script>
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
setTitle(data)
}
});
function setTitle(raw_data){
let newTitle;
let chart = Highcharts.chart('container', {
chart: {
zoomType: 'xy',
events: {
load: function() {
this.update({
title: {
text: 'Airmeter: '+ newTitle
}
})
}
}
},
xAxis:{
title:{
text: 'Zeit'
}
},
yAxis:{
title:{
text: 'CO2 in ppm'
}
} ,
exporting:{
enabled: true
},
title: {
text: null
},
credits:{
enabled: false
},
data: {
csv: raw_data,
parsed(e) {
newTitle=e[0][1] //set the first column as title of the chart
e.shift()
}
}
});
}
</script>
</body>
</html>
我真的很感激幫助。 感謝您的寶貴時間,祝您有美好的一天!
If the CSV will always be on your local machine rather than a server, you don't really need to be using an AJAX call and you could use the FileAPI and a CSV parser to pass the data to your setTitle
function.
但是為了幫助您的方法,請嘗試對您的代碼進行以下更改:
在代碼更改方面(未經測試):
<script>
// Add an event listener, so when a file is selected, the graph is drawn again
document.getElementById("input").addEventListener("change", drawGraph, false);
// Wrap your current AJAX call in the event handler
function drawGraph() {
// Obtain the name of the file selected by the user in the <input>
var fileName = document.getElementById('input').files[0].name;
$.ajax({
type: "GET",
url: fileName, // use this name to fetch the selected file
success: function (data) {
setTitle(data)
}
});
}
// Leave the rest of the script block as it is
// ...
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.