2012-10-25 70 views
0

可能重複:
Deserializing JavaScript object instance如何發送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' 
}); 

但我得到一個空數組服務器。任何人都可以告訴我我失蹤了什麼?

EDIT

的console.log(jObejctArray)輸出是(數組2 obejct):

[ 
{"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":[]} 
] 
+0

你能先做到這一點'的console.log (jObjectAray)'並告訴我們你得到的是什麼 – 2619

+0

@ al0neevenings請檢查我的編輯 –

回答

0

敲除觀測不是簡單的領域,而功能。函數不會被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; 
} 
+0

而不是創建自我toJson fucntion我使用inbuilt ko.toJSON,但我仍然獲得相同的空數組到服務器,我把'console.log (jObjectArray)'我的編輯輸出請看看 –

+0

,你有沒有試過我寫的東西? –

相關問題