2015-08-24 34 views
0

流星中的新增功能。流星中的打印對象

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結果的實際值?

謝謝

+0

我承認這個ISN '__exact__重複,因爲這個問題是關於一個ajax調用,但是問題和解決方案是相同的:你有一個異步調用是在一個必須同步運行的助手中進行的。 –

回答

1

因爲在流星,對象會叫「的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> 

我希望它可以幫助你解決你的問題:-)