jquery - 将带有对象的数组转换为 JSONstring

标签 jquery ajax arrays object backbone.js

我使用 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/

相关文章:

javascript - 在 div 中包装 slider 降低高度

javascript - 如何在第一次点击时获得正确的百分比?

jquery - 在自己的位置弹跳 div?

javascript - Kendo grid 错误 : kendo. all.min.js :12 Uncaught TypeError: e. slice is not a function

javascript - 如何在 JavaScript 上为对象列表创建循环

php - 单击图像时需要打开 bpopup

jquery - 防止未处理的 jQuery AJAX 错误

java - 将 javascript 数组传递给 java servlet

PHP array_merge 不工作

java - 在 Java 中向数组添加项目