如何将数组传递给 post 方法在 this.collection.create in backbone.



我在我的 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 属性设置数组地址,但在创建时会给出此错误。
未捕获的类型错误:将循环结构转换为 JSON 

请指导。

该错误仅表示您已经创建了一个自引用对象(此类对象不可能序列化为 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下创建一个模型的副本,即,如果模型是{ prop: "val", prop2: "val2" },那么你最终会得到:

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

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

相关内容

最新更新