【问题标题】:Printing object in meteor [duplicate]在流星中打印对象[重复]
【发布时间】:2015-11-17 08:21:12
【问题描述】:

我是新的流星。

This is my javascript code
Template.data.helpers({
  data_res: function () {
  //DoChart();
  //var a = "aaaa";
  //return a;
  var a = $.ajax({
   method: "post",
   url: "http://10.102.4.232:124/getdata.asmx/GetCabang",
   data: '',
   contentType: "application/json",
   success: function (data) {
   console.log(data); // 6
  }
  });
  return a;
 }
});
This is my template code 
<template name="data">
{{data_res}}
</template>

javascript 代码是请求 Web 服务视图 ajax 并将其打印在我的模板中。但在我的模板中,结果是 [object Object]。

我的问题是如何在模板中打印 ajax 结果的实际值???

谢谢

【问题讨论】:

  • 我承认这不是 exact 重复,因为这个问题是关于 ajax 调用的,但是问题和解决方案是相同的:你有一个异步调用在必须同步运行的助手中制作。

标签: meteor


【解决方案1】:

因为在 Meteor 中,对象会在模板渲染之前调用 'toString' 方法。所以我们不能用这种方式打印一个对象,但是你可以:

// Call your ajax method in this place, or in other place you want
Template.data.onCreated(function(){
  // Using Session to storage ajax response, which will render template automatically when it changed
  Session.setDefault('myObject', 'no-response');
  $.ajax({
    method: "post",
    url: "http://10.102.4.232:124/getdata.asmx/GetCabang",
    data: '',
    contentType: "application/json",
    success: function (data) {
      console.log(data); // 6
      Session.set('myObject', data)
   }
 });
});


Template.data.helpers({
  // When receive ajax response, set it to Session 'myObject', and it would render your template 'data' reactively
  data_res: function () {
    return Session.get('myObject');
  }
});
This is my template code 
<template name="data">  // using '.' to get property in your object
  {{data_res.propertyA}} {{data_res.propertyB}} {{data_res.propertyC}}
</template>

希望它能帮助您解决问题:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 2023-03-27
    • 1970-01-01
    • 2019-02-01
    • 2012-02-02
    • 2015-09-15
    • 2015-07-16
    • 2014-03-08
    相关资源
    最近更新 更多