通过js中的url解析json数据

时间:2016-07-05 16:41:09

标签: javascript json

我正在尝试解析来自JSON url链接的数据。我很困惑如何让我的js读取数组并放入一个canvas标签来创建一个条形图。我只想使用js而不是jQuery。这是我的代码和注释说明。这是JSON:

[{ "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`

2 个答案:

答案 0 :(得分:0)

您提供的JSON只有一个对象。该对象中包含item01-item04。

考虑使用像这样的json:

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

在这种情况下,arr.data是您需要的真实数组。

答案 1 :(得分:0)

您的myFunction()方法看起来似乎期望传递的相同数据结构(单个成员数组)保存您的对象。那为什么会尝试循环包装数组呢?

该对象本身没有名为label的属性,因此您将始终将空字符串连接到out变量。