我使用 ajaxCall 返回一个数组,如下所示: http://d.pr/i/ojR4
对象内部是 Json (例如: http://d.pr/i/aAM2 ) 当我将其推送到我的 .hbs 文件(主干)时,不可能循环它,因为它是一个数组,并且它只接受纯 JSON。
有什么方法可以将其完全转换为 JSON 吗?
我的渲染函数在下面的 View 中:
render: function(){
var self = this;
var tripData;
console.log("[TripListView] render");
$.ajax({
url: Util.api + "/getalltrips",
type:"GET",
success: function(data){
console.log(data); // This is the output given
tripData = data;
}, error:function(){
console.log(arguments);
}
});
$('#container').html(this.template({trips: data}));
return this;
}
最佳答案
如果无法发送数组,请将其包装在对象中并使用它。但原因可能是因为在 AJAX 调用之外访问数据。
$('#container').html(this.template({trips: data}));<-- here data would be undefined
试试这个:-
var self = this
success: function(data){
console.log(data); // This is the output given
tripData = {tripsResponse:data};// You probably don't need this since your actual issue might be accessing `data` below the ajax call.
$('#container').html(self.template({trips: tripData })); // I have moved this here since placing this after ajax call doesn't make sense, as it would have got executed before your callback.
}
//....
关于jquery - 将带有对象的数组转换为 JSONstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703796/