2014-01-18 20 views
0

警告:可能是一個愚蠢的問題。爲什麼我的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。

+2

什麼是理想的結果呢? – skmasq

+0

爲什麼你需要聲明這個'self.selectedOrgCountry = ko.observable();'兩次? – skmasq

+0

期望的結果是具有鍵的對象:「1」,名稱:「國家名稱」。我是否將ko數組聲明兩次? – ledgeJumper

回答

2

$.each is defined as follows:

jQuery.each(收集,回調(indexInArray,valueOfElement))

這意味着當你撥打:

$.each(data, function (name, key) { ... 

您遍歷每個元素在數據數組中。上面的name參數將被設置爲它正在迭代的元素的當前索引,key是值。 jQuery確實不是讀取參數名稱並填寫值。

什麼你要找的就是這個

$.each(data, function (index, element) { 
    var name = element.name; 
    var key = element.key; 
+0

啊,感謝您發表了一些參考。看到我的編輯,我意外發現了這一個,並不確定它爲什麼起作用。 – ledgeJumper

相關問題