2013-09-28 92 views
6

比方說,我有一個後端服務層這個數據返回:JQuery的填充的DropDownList與JSON數據

[「2」,「3」,「7」,「14」]

第一個問題。這是否被認爲是有效的JSON數據? Json.org說這是,但我找不到任何在谷歌,SO等參考......

值的有序列表。在大多數語言中,這是作爲數組,矢量,列表或序列實現的。

我希望能夠接受這些值並將它們添加到使用JQuery的已存在的DropDownList對象OnLoad中。

$.getJSON(「http://www.example.com/path-to-get-data」, function(data) { 
    //iterate through each object and add it to the list. 
    //ideally, the key and value (string to display to the end user) would be the same. 
}); 

我看了看this thread,但它有對象,不只是一個數組。我應該使用parseJSONgetJSON

在此先感謝!

+0

我相信這是無效的,有效的JSON將會像{「鍵‘2’, 」關鍵「:‘3’, 」關鍵「:‘7’, 」重點「: 「14」} – Satya

+0

'$ .parseJSON( '[ 「2」, 「3」, 「7」, 「14」]')'將返回的數組。更好地使用getJSON並迭代數組中的每個項目並將其添加到對象中 – rzr

回答

9
var arr = [ 2, 3, 7, 14]; 
$.each(arr, function(index, value) { 
    ('#myselect').append($('<option>').text(value).attr('value', index)); 
}); 

也請看一看C君的解決方案:

$('<option></option>').val(item).html(item) 

他操縱option s是新的我的方式,和更優雅。

+0

它拋出「對象不支持.append」 – Kurkula

+1

什麼是您的jQuery版本和什麼是您的瀏覽器? – Blaise

+0

ie 11. jquery邊緣。 – Kurkula

2

這是不正確的JSON,它必須是此風格:

{"0": "2", "1" : "3", "2" : "7", "3" : "14"} 

您可以使用該樣本procceed您迴應:

var response = "[2, 3, 7, 14]"; 
eval("var tmp = " + response); 
console.log(tmp); 
5

我的解決方案是基於斷Blaise's想法。

//populate the Drop Down List 
$.getJSON("http://www.example.com/api/service", function (data) { 
    $.each(data, function (index, item) { 
     $('#dropDownList').append(
       $('<option></option>').val(item).html(item) 
     ); 
    }); 
}); 
1

這是HiddenField聲明,這是存儲JSON字符串

<asp:HiddenField ID="hdnBankStatus" runat="server" /> 

這是DROPDOWNLIST聲明

<select id="optStatus" name="optStatus" runat="server"> 
     </select> 

這些線路將初始化Hiddenfield值與排序列表非常有用(假定列表包含按排序順序的關鍵值對),然後使用JSON序列

序列化條
sl = new SortedList(); 
    hdnBankStatus.Value = jsonSerialiser.Serialize(sl); 

這些線路將一個使用JSON字符串的一個元素和填充值的下拉列表。

$(document).ready(function() { 

    var myOptions = $.parseJSON($('#hdnBankStatus').val()); 
     var mySelect = $('#optStatus'); 
     $.each(myOptions, function (val, text) { 
      mySelect.append(
    $('<option></option>').val(text).html(val) 
     ); 
     }); 
    } 
-3

對我來說,這一個工作。

$("#ddlCaseType").append("<option>" + txt + "</option>"); 
+0

$(「#ddlCaseType」)。append(「」); –

0
var arr = [ 2, 3, 7, 14]; 
var dropdown = ('#myselect'); 
dropdown.empty(); 
dropdown.append($('<option value=''>--Please Select--</option>')); 
$.each(arr, function(index, value) { 
dropdown.append($('<option value='+index+'>'+value+'</option>')); 
});` 
+0

這應該這樣做 –