使用来自网址的JSON填充Meteor中的Select Drop Down?

时间:2015-01-20 00:08:29

标签: javascript json meteor

如何使用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)进行选择下拉,当用户进行选择时,将显示winsnumbers。

你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

此代码将执行此操作: 我已将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); 
  }
}
&#13;
<select  id="selectDate">
  
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以在Template.rendered中调用服务器端方法并动态创建一些html元素

 Template.resultsView.rendered=function(){
     Meteor.call('getData',function(err,result){
      if(err){
       //Error handling code
      }else{
       var myDynamicHtml = '<option value='' default>Select a date</option>';
       result.forEach(function(el,index){
          //create you dom elements with the parsed data on results
          // append to any container with specific id
           myDynamicHtml+= "<option value='"+ele.someProperty+"' </option>";
       });
      $('#idOfContainer').html(myDynamicHtml);
       //idOfContainer is the id of html elment in template resultView where you 
       //want show the parsed data in any(<select>) html element
      }
     }); 
 }