警告:可能是一個愚蠢的問題。爲什麼我的ajax GET數據製作奇怪的JSON對象?
我有一個Ajax GET請求,就像這樣:
$.getJSON("/recruiting/countries/all/", function (data) {
$.each(data, function (name, key) {
var dropdownCountry = new DropdownCountry();
dropdownCountry.name = name;
dropdownCountry.key = key;
self.orgCountryDdl.push(dropdownCountry);
});
alert(JSON.stringify(self.orgCountryDdl()));
});
它擊中一個URL和具有國家的列表:名稱和關鍵。
我想分配數據,並最終填充一個國家列表的基因敲除js可觀察數組。其他的JavaScript代碼,在此GET請求引用:
var DropdownCountry = function (name, key) {
this.name = name;
this.key = key;
};
function UserRecruitingViewModel(apiBaseUrl, userId) {
var self =this;
//...snip...
//ddl country stuff
self.orgCountryDdl = ko.observableArray();
self.selectedOrgCountry = ko.observable();
var DropdownCountry = function (name, key) {
this.name = name;
this.key = key;
};
self.selectedOrgCountry = ko.observable();
///..get request in here...
};
在警報
我有我看到這個數據回來:
[
{"name":0,"key":{"Id":1,"Name":"Albania"}}
,{"name":1,"key":{"Id":2,"Name":"Algeria"}}
,{"name":2,"key":{"Id":3,"Name":"American Samoa"}}
,{"name":3,"key":{"Id":4,"Name":"Andorra"}}
,{"name":4,"key":{"Id":5,"Name":"Angola"}}
,{"name":5,"key":{"Id":6,"Name":"Anguilla"}}
,{"name":6,"key":{"Id":7,"Name":"Antarctica"}}
...snip...
]
這是怎麼回事,什麼是最徹底的方法把它變成一個可觀的數組?
對不起:期望的結果是這樣的數據:
[
{"Id":1,"Name":"Albania"}
,{"Id":2,"Name":"Algeria"}
,{"Id":3,"Name":"American Samoa"}
...snip...
]
其實我想通了事故:
$.getJSON("/recruiting/countries/all/", function (data) {
$.each(data, function (name, key) {
var dropdownCountry = new DropdownCountry();
dropdownCountry.name = key.Name;
dropdownCountry.key = key.Id;
self.orgCountryDdl.push(dropdownCountry);
});
alert(JSON.stringify(self.orgCountryDdl()));
});
第二個函數變量有我想要的數據。有人可以解釋爲什麼嗎?我對ajax電話很新奇,所以我甚至不知道該怎麼去google。
什麼是理想的結果呢? – skmasq
爲什麼你需要聲明這個'self.selectedOrgCountry = ko.observable();'兩次? – skmasq
期望的結果是具有鍵的對象:「1」,名稱:「國家名稱」。我是否將ko數組聲明兩次? – ledgeJumper