2014-03-28 336 views
0

我是javascript的noob,我想弄清楚如何从url中获取JSON数据并将其组织成关于本月的可视化表示。这里的问题是:从JSON url获取

数据:https://api.goodwillwa.org/stores?group_level=3

{ 
    key: [ 
    year, 
    month, 
    day 
    ], 

    value: [ 
    totalTransactions, 
    totalSales, 
    totalDiscounts, 
    totalItemsSold 
    ] 
} 

目的:用客户端JavaScript获取JSON数据并按月创建 数据的可视化。你可以使用任何你觉得有用的库。为了简洁起见,加分。

我把一切都变成一个网页,并试图将它写出来的网页上:

<!DOCTYPE html) 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Code Test</title> 

    </head> 
    <body> 
     <h1 id="title">This is the month</h1> 
     <script> 
      function codeTest(key, value) 
      { 
      // code will fetch the json data structure and disply it in the html document 


      } 

     </script> 
     <p id="new"></p> 
     <button type="button" onclick="codeTest()"> Display information</button> 
    </body> 
</html> 

我想使它看起来空白,直到按下一个按钮,这将导致它显示在屏幕。谁能帮我吗?

+1

你有什么试过?到目前为止,你有一个空的函数,编写了任何代码来尝试从远程URL加载? – shortstuffsushi

+0

var url =“https://api.goodwillwa.org/stores?group_level=3”; $ .getJSON(url,function(data){ alert(data); }); 我对这种语言很陌生。我甚至还没有开始考虑如何在文档中格式化它。我只是想弄清楚如何检索信息。 – user3470798

回答

0

在你的onclick属性中,当你定义codeTest需要一个key和value又名codeTest(key,value)时,你为codeTest()分配一个调用,但参数是空的(在括号内没有任何内容)。

从我了解你想codeTest采取任何参数,如下所示:

function codetest(){ 
    $.ajax({ 
     url:your url in "string" format, 
     dataType:"json" 
     "success":function(resp){ 
      // resp is an object 
      // so you do resp.key to get the associated value 
      // so assign the data you get in resp to variables you have in your webpage JS 
      // then assign your HTML values to the JS variables 
     } 
    }); 
} 

您的网址应为您服务字符串化版本的JSON数据。

您可能希望将数据重新格式化为:

{ 
    //key:value 
    "year":"2014", 
    "month":"march", 
    "day":"27", 
    "totalTransactions":"alot", 
    "totalSales":"starbucks level", 
    "totalDiscounts":"none hehe", 
    "totalItemsSold":"alot alot" 

} 

这是数据的一个JSON“对象” ......如果你有更多的,那么你需要这些对象的数组和略有不同的方法。让我知道 - Niko hth

+0

请注意,这是一个jquery解决方案 –

+0

哦,对,然后OP考虑在您的原始