0

可能重复:
反序列化 JavaScript 对象实例

我在 javascript 中有一组以下构造函数对象:

 function MenuViewModel() {
    var self = this;
    var courseOptionObject = {};

    courseOptionObject["Options"] = [];
    self.ShowHide = ko.observable(false);

        self.Id = ko.observable(getId()); 
        self.Name = ko.observable();
        self.CourseName = ko.observable();
        self.Sequence = ko.observable('1');

        courseOptionObject["MenuId"] = self.Id();
        self.CourseOptions = ko.observable(new CourseOptionViewModel(courseOptionObject));                                             

    if (typeof MenuViewModel.saveButtonControll == "undefined") { //static members of class
        MenuViewModel.saveButtonControll = ko.observable(new buttonModel({ Text: "Save & Continue", Disabled: true, Visible: true }));
        MenuViewModel.IsTextEnable = ko.observable(true);
    }

    self.showDeleteIcon = function (data, event) { 
       data.ShowHide(true); 
    };

    //Hide the delete button from the menu ( call at mouseleave form the menu )
    self.hideDeleteIcon = function (data, event) {
        data.ShowHide(false); 
    };

    self.Errors = ko.validation.group(self);
}

我的数组是:

var jObectArray = new Array();
for(var i = 0; i < 5; i++)
{
 jObejctArray.push(new MenuViewModel());
}

我通过 ajax 发送它:

$.ajax({
   url :'urltoserver',
   type: 'POST',
   data: { array : JSON.stringify(jObectArray) },
   dataType: 'JSON'
 });

但我得到一个空数组到服务器。谁能告诉我我错过了什么?

编辑

console.log(jObejctArray) 输出为(数组中的 2 个对象):

[
{"ShowHide":false,"Id":"8c4c470d-2b25-4070-8d3e-e307e9d49107",
"Name":"Menu-1","CourseName":"course-1","Sequence":1,
"CourseOptions":{"MenuId":"8c4c470d-2b25-4070-8d3e-e307e9d49107",
"Options":[],"errors":["Can`t left options list empty","Can`t insert empty value."],
"Errors":["Can`t left options list empty","Can`t insert empty value."]},
"errors":[],"Errors":[]},

{"ShowHide":false,"Id":"3da9cbc0-9db8-4297-8245-351caaec9f08",
 "Name":"Menu-2","CourseName":"course-2","Sequence":"2",
 "CourseOptions":{"MenuId":"3da9cbc0-9db8-4297-8245-351caaec9f08",
 "Options":[],"errors":["Can`t left options list empty","Can`t insert empty value."],
 "Errors":["Can`t left options list empty","Can`t insert empty value."]},
 "errors":[],"Errors":[]}
] 
4

1 回答 1

0

Knockout observables 不是简单的字段,而是函数。JSON.stringify 不处理函数。通过使用添加 toJSON 方法指定自定义序列化程序来覆盖默认字符串化行为(这将由 JSON.stringify 调用)

尝试将此添加到您的模型中:

self.toJSON = function()  {
   var result = {};
   result.Name  = ko.utils.unwrapObservable(self.Name);
   ...
   /// you could either iterate over the fields with `for .. in`
   return result;
}
于 2012-10-25T10:43:06.250 回答