2015-10-22 30 views
1

請幫幫我。有一個JavaScript代碼,我製作一個畫布圖。該圖的數據是靜態的,但我想從.txt文件加載這些數據。你知不知道怎麼?謝謝!如何從.txt將數據加載到javascript中

<script type="text/javascript"> 

var canvas ; 
var context ; 
var Val_max; 
var Val_min; 
var sections; 
var xScale; 
var yScale; 



     // Values for the Data Plot, they can also be obtained from a external file 
var data =[0,10,20,40,50,100,120,130,0]; 



function init() { 
     // set these values for your data 
    sections = 12; 
    Val_max = 130; 
    Val_min = -40; 
    var stepSize = 10; 
    var columnSize = 50; 
    var rowSize = 50; 
    var margin = 10; 
    var xAxis = [" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
     // 

    canvas = document.getElementById("canvas"); 
    context = canvas.getContext("2d"); 
    context.fillStyle = "#0099ff" 
    context.font = "20 pt Verdana" 

    yScale = (canvas.height - columnSize - margin)/(Val_max - Val_min); 
    xScale = (canvas.width - rowSize)/sections; 

    context.strokeStyle="#009933"; // color of grid lines 
    context.beginPath(); 
     // print Parameters on X axis, and grid lines on the graph 
    for (i=1;i<=sections;i++) { 
     var x = i * xScale; 
     context.fillText(xAxis[i], x,columnSize - margin); 
     context.moveTo(x, columnSize); 
     context.lineTo(x, canvas.height - margin); 
    } 

回答

1

對於加載文件,試試這個:

function request (path, onload) { 
    var req = new XMLHttpRequest(); 
    req.onload = function() { 
     return onload(this.responseText); 
    }; 
    req.open("GET", path, true); 
    req.send(); 
} 

及用途:

request('http://yousite.com/text.txt',function(response){ 
    //code here 
}); 
+0

,將在功能反應是什麼?這是爲什麼呢? –

+0

@MílaSkipperMoravecResponse是url請求文件的內容。 – James

相關問題