【问题标题】:Populate html table with http API request in Meteor在 Meteor 中使用 http API 请求填充 html 表
【发布时间】:2016-10-12 04:44:11
【问题描述】:

我有一张桌子

<table>
 <thead>
  <tr>
   <th>Year</th>
   <th>Value</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>1990</td>
   <td>-</td>
  </tr>
  ...
 </tbody>
</table>

我想向 World Bank API 发出 GET 请求以填写此表中的值。

我的 GET 请求在 Meteor 方法中

Meteor.methods({
  getData: function () {
    try {
      const url = 'http://api.worldbank.org/countries/br/indicators/NY.GDP.MKTP.CD?date=1990:2000&format=json';
      const request = HTTP.get(url);
      return request;
    } catch (e) {
      console.log(e);
      return false;
    }
  },
});

我从客户端调用我的方法

Meteor.call('getData', function(error, result) {
  console.log(result);
});

所以我得到了控制台中的值,但我想用正确的值替换 html 表中的-

【问题讨论】:

    标签: javascript html node.js servlets meteor


    【解决方案1】:

    您将使用 {{#each}} 块助手循环遍历数组。例如

    <tbody>
     {{#each getData}}
     <tr>
      <td>{{date}}</td>
      <td>{{value}}</td>
     </tr>
     {{/each}}
    </tbody>
    

    其中getData 是获取数据的模板助手。但是,由于您获取的数据是异步的,因此您不能简单地在帮助程序中直接执行 Meteor.call()

    解决此问题的一种方法是使用会话变量('meteor add session' 来安装包)。

    首先,您将在创建模板时获取数据并将其设置为会话变量:

    Template.your_template.onCreated(function() {
        Meteor.call('getData', function(error, result) {
            // result.data[1] is the array of objects with the data
            Session.set('bankData', result.data[1]);
        });
    });
    

    然后,使用模板助手将数据传递给模板:

    Template.your_template.helpers({
        getData: function(){        
            return Session.get('bankData');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      相关资源
      最近更新 更多