也是最近遇到的需求,算是綜合題,想要在網頁上用 ajax 動態上傳檔案後並馬上繪製出圖表,結合 jquery 跟 d3.js。
用 bootstrap 來畫的,所以先準備 html。
- <form class="form-inline">
- <div class="form-group">
- <label for="">上傳 csv: </label><input name="csv_file" type="file" id="csv_file">
- </div>
- <a role="button" class="btn btn-primary" id="upload_csv">確認上傳</a>
- </form>
- <div id="chart"></div>
code 都在這邊,想用在自己拿去改,簡單的說就是上傳後把 csv 用 d3 處理後再把圖表畫出來就可以了,範例使用 d3.js 的 3d 甜甜圈。
- $("#upload_csv").click(uploadCsv);
- function uploadCsv(){
- //file object
- csv = $("#csv_file")[0].files;
- var data = new FormData();
- data.append("csv_file", csv[0]);
- $.ajax({
- url: "handle url",
- type: 'POST',
- data: data,
- cache: false,
- processData: false, // Don't process the files
- contentType: false, // Set content type to false as jQuery will tell the server its a query string request
- success: function(data, textStatus, jqXHR)
- {
- $csvData="upload/"+data;
- d3.csv($csvData, function(data) {
- arrayLength=list.length;
- for($i=0;$i<arrayLength;$i++){
- list[$i]["color"]=color($i);
- }
- svg.remove();
- svg = d3.select("#chart").append("svg").attr("width",400).attr("height",300);
- svg.append("g").attr("id", "salesDonut");
- Donut3D.draw("salesDonut", list, 150, 150, 130, 100, 30, 0.4);
- var info = svg.selectAll("g.info")
- .data(list)
- .enter()
- .append("g")
- .attr("class", "info")
- .attr("transform", "translate(" + 300 + "," + 50 + ")");
- info.append("text")
- .attr("x", 10)
- .attr("y", function(d, i){
- return i*24;
- })
- .attr("fill", function(d, i) {
- return color(i);
- })
- .text(function(d, i) {
- return d.label+": "+d.value;
- });
- });
- if(typeof data.error === 'undefined')
- {
- // Success so call function to process the form
- }
- else
- {
- // Handle errors here
- console.log('ERRORS: ' + data.error);
- }
- },
- error: function(jqXHR, textStatus, errorThrown)
- {
- // Handle errors here
- console.log('ERRORS: ' + textStatus);
- // STOP LOADING SPINNER
- }
- });
- }