0

我在我的 mvc 应用程序中使用了主干.js,我有一个场景,我必须将一个数组传递给我在 Rest API 中的 Post 方法。我试图在我的模型中设置一个数组属性,然后调用 this.collection.create(model)。我正在使用这样的模型的属性

默认值:{
            地址: '',
            城市: '',
            状态: '',
            压缩: '',
            地址数组:[]
        }
  
并尝试将 Post 方法称为
    e.models[0].set({ 'AddressArray': e.models});
    this.collection.create(e.models[0]);
    
这里 e.models[0] 是我的模型对象,而 e.models 是一个模型数组。set 属性设置数组地址,但在创建时它给出了这个错误。

未捕获的 TypeError:将循环结构转换为 JSON

请指导。

4

1 回答 1

0

该错误仅表示您创建了一个自引用对象(无法序列化为 JSON)。即,您已经完成了与此等效的操作:

var x = {};
x['test'] = x;
JSON.stringify(x); // TypeError: Converting circular structure to JSON

您可以先使用创建模型的副本toJSON,以便对象不引用自身:

var json = e.models[0].toJSON();
json['AddressArray'] = e.models[0].attributes;
this.collection.create(json);

但这不太有意义,因为.attributes指的是模型的属性,所以您所做的只是在 下创建模型的副本AddressArray,即如果模型是 say { prop: "val", prop2: "val2" },那么您最终会得到:

{
    prop: "val",
    prop2: "val2",
    AddressArray: {
        prop: "val",
        prop2: "val2",
    }
}

无论哪种方式,您都无法将引用自身的对象转换为 JSON;并且需要序列化通过调用将模型保存到服务器Collection.create

于 2012-12-10T07:27:36.310 回答