如何使用 Meteor 和位于以下位置的以下 JSON 创建近期彩票结果页面: LOTTERY DATA
以下代码会成功调用数据,如控制台所示,但我不够聪明,无法弄清楚如何将此数据显示到 Meteor 的页面上。
Meteor.http.call("GET", "http://data.ny.gov/resource/d6yy-54nr.json", function (err, result){
my_json = result.content;
console.log(my_json);
});
控制台正在记录以下内容:
[ {
"draw_date" : "2015-01-17T00:00:00",
"winning_numbers" : "15 16 23 27 36 09",
"multiplier" : "2"
}
, {
"draw_date" : "2015-01-14T00:00:00",
"winning_numbers" : "02 04 10 41 53 22",
"multiplier" : "5"
}
, {
"draw_date" : "2015-01-10T00:00:00",
"winning_numbers" : "02 09 19 28 29 19",
"multiplier" : "5"
}
最初只要在页面上显示任何结果就很棒了。但理想情况下,我希望能够有一个包含所有可用 draw_date(s)
的选择下拉菜单,并且当用户做出选择时,将显示中奖号码。
你能帮我解决这个问题吗?
最佳答案
这段代码将做到这一点: 我已将 JSON 的结果用作硬编码对象,因为 Meteor 无法作为外部库加载。
var showData = [ {
"draw_date" : "2015-01-17T00:00:00",
"winning_numbers" : "15 16 23 27 36 09",
"multiplier" : "2"
}
, {
"draw_date" : "2015-01-14T00:00:00",
"winning_numbers" : "02 04 10 41 53 22",
"multiplier" : "5"
}
, {
"draw_date" : "2015-01-10T00:00:00",
"winning_numbers" : "02 09 19 28 29 19",
"multiplier" : "5"
}];
//set a default option to the select.
var html = "<option value='' disabled default>Select a date</option>";
//iterate over each lottery drawing and add it to the select.
//The date will be displayed, the index of the array element will be the value.
showData.forEach(function(element, index){
var date = new Date(element.draw_date);
html += "<option value='"+index+"'>"+ date.getDate() + "/" + (parseInt(date.getMonth())+1) + "/" + date.getFullYear()+ "</option>";
});
//insert the option into the select.
document.getElementById("selectDate").insertAdjacentHTML("beforeend", html);
//add an onchange event handler to the select.
document.getElementById("selectDate").addEventListener("change", displayWinningNumbers, false);
function displayWinningNumbers(e)
{
//when a option is selected, test the value. If 0 or higher return the array entry with the winning numbers.
if(e.target.value >= 0)
{
alert(showData[e.target.value].winning_numbers);
}
}
<select id="selectDate">
</select>
关于javascript - 使用来自 url 的 JSON 填充 Meteor 中的选择下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035709/