2016-07-05 173 views
0

我想解析來自JSON網址鏈接的數據。我很困惑如何讓我的js讀取數組並將其放入畫布標記以創建條形圖。我只想使用js而不是jQuery。這是我的代碼和評論筆記。這裏的JSON:解析JSON數據通過URL在js

[{ "title":"Random Information", "item01":"29", "item02":"41", "item03":"7", "item04":"42", "item05":"11" }]

<html> 
<head> 
<title>barchart</title> 
<script> 
window.onload = function() { 

//var arr = [20, 40, 50, 100, 150]; the barchart shows up with set array 

var xmlhttp = new XMLHttpRequest(); 
var url = "https://myurl"; 

xmlhttp.onreadystatechange = function() { 
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
    var myArr = JSON.parse(xmlhttp.responseText); 
    myFunction(myArr); 
} 
}; 
xmlhttp.open("GET", url, true); 
xmlhttp.send(); 

var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); 
var x = 20 
var y = 300 
var width = 50 
var height; 
var arr = []; 

function myFunction(arr) { 
var out = ""; 
var i; 
for (i = 0; i < arr.length; i++) { 
out += arr[i].label; 
} 

document.getElementById("data").innerHTML = out; 
} 

ctx.fillStyle = "#000000"; 
ctx.fillRect(x,y-arr[0],width, arr[0]); //should this be arr[0].value to control height of bar - didn't work 
ctx.font = "20px Arial"; 
ctx.fillStyle = "#000000"; 
ctx.fillText(arr[0], x+15, y+25); //should this be arr[0].label to show the title of the bar - didn't work 

ctx.fillStyle = "#ff00ff"; 
ctx.fillRect(x+55, y-arr[1], width, arr[1]); 
ctx.font = "20px Arial"; 
ctx.fillStyle = "#000000"; 
ctx.fillText(arr[1], x+70, y+25); 

ctx.fillStyle = "#32cd32"; 
ctx.fillRect(x+110, y-arr[2], width, arr[2]); 
ctx.font = "20px Arial"; 
ctx.fillStyle = "#000000"; 
ctx.fillText(arr[2], x+125, y+25); 

ctx.fillStyle = "#ff9933"; 
ctx.fillRect(x+165, y-arr[3], width, arr[3]); 
ctx.font = "20px Arial"; 
ctx.fillStyle = "#000000"; 
ctx.fillText(arr[3], x+170, y+25); 

ctx.fillStyle = "#f3f315"; 
ctx.fillRect(x+220, y-arr[4], width, arr[4]); 
ctx.font = "20px Arial"; 
ctx.fillStyle = "#000000"; 
ctx.fillText(arr[4], x+230, y+25); 

ctx.stroke() 
} 

</script> 
</head> 
<body> 
<canvas id="myCanvas" width="700" height="550" style="border: 1px  solid #d3d3d3;"> Your browser doesn't support the HTML5 canvas tag</canvas> 
<div id = "data"></div> 
</body> 
</html>`enter code here` 
+0

歡迎來到Stack Overflow!你能詳細說明你的代碼「不起作用」嗎?你在期待什麼,究竟發生了什麼?如果您遇到異常或錯誤,請發佈其發生的行和詳細信息。請[編輯]這些細節或我們可能無法提供幫助。 –

+0

'label'和'value'不會出現在您的JSON中,因此它們將會是未定義的。 – 4castle

+0

'out'不存在於'myFunction'函數之外。您需要執行與該函數內'out' *有關的所有代碼。 –

回答

0

,你只提供中有一個對象的JSON。並且該對象中有item01-item04。

考慮使用JSON這樣的:

{ 
    "title": "Random Information", 
    "data": [29, 41, 7, 42, 11] 
} 

在這種情況下,arr.data是,你需要真正的數組。

+0

謝謝!我不明白我的所有信息都會用arr [0]調用,現在通過添加 - item01 = arr [0] .item01;將其應用於我的代碼。 – Jane123

0

你的myFunction()方法似乎期望傳遞相同的數據結構,它是一個單一的成員數組,持有你的對象。爲什麼然後會嘗試循環包裝數組?

該對象本身沒有名爲label的屬性,因此您總是會獲得空字符串,並將其專用於out變量。