将带对象的数组转换为JSONstring

时间:2013-05-23 00:33:55

标签: jquery ajax arrays object backbone.js

我返回一个带有我的ajaxCall的数组,如下所示: http://d.pr/i/ojR4

对象内部是Json(例如:http://d.pr/i/aAM2) 当我把它推到我的.hbs文件(主干)时,它不可能循环它,因为它是一个数组,它只接受普通的JSON。

有没有办法将它完全转换为JSON?

我在以下视图中的渲染功能:

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;
}

2 个答案:

答案 0 :(得分:1)

如果您无法发送数组将其包装在对象中并使用它。但原因可能是因为在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.
        }
       //....

答案 1 :(得分:0)

我不确定你的问题是什么,但我会猜测。如果您创建Dictionary<object, object>并将键设置为某些字符串(如“data”)并将值设置为数组,则在序列化它时,您将获得一个JSON对象。这是一个简短的例子:

var theList = new List<string>();
var theDict = new Dictionary<string, object>();
theDict.Add("data", theList);