Javascript 如何使用 JSON 数据填充选择框的选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5918144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use JSON data to populate the options of a select box?
提问by Pizdabol
I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.
我需要根据选择的国家/地区来喂养城市。我以编程方式完成,但不知道如何将 JSON 数据放入选择框中。我尝试了几种使用 jQuery 的方法,但都没有奏效。
The response I am getting (I can format this differently if necessary):
我得到的回应(如有必要,我可以采用不同的格式):
["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]
But how can I put this data as options inside a HTML <select></select>
tag?
但是如何将这些数据作为选项放入 HTML<select></select>
标签中呢?
The code I tried:
我试过的代码:
<form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>
</div>
<script>
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$('#myselect').append(json);
}
});
};
$( '.suggest' ).keyup( function() {
getResults( $( this ).val() );
} );
</script>
I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.
我还尝试使用本教程使用 jQuery 和 AJAX 自动填充选择框,但除了用“未定义”填充我的选择之外,这从来没有做任何事情,即使我得到了教程建议的格式的响应。
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#city").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#myselect").html(options);
})
})
})
</script>
回答by Samir Talwar
Why not just make the server return the names?
为什么不让服务器返回名称?
["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]
Then create the <option>
elements using JavaScript.
然后<option>
使用 JavaScript创建元素。
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
回答by zeusstl
Given returned json from your://site.com:
鉴于从您的://site.com 返回的 json:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
用这个:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
回答by Edgar Villegas Alvarado
You should do it like this:
你应该这样做:
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, optionHtml){
$('#myselect').append(optionHtml);
});
}
});
};
Cheers
干杯
回答by Jovan MSFT
Take a look at JQuery view engineand just load the array into a dropdown:
看看JQuery 视图引擎,然后将数组加载到下拉列表中:
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
// Assumption is that API returned something like:["North","West","South","East"];
$('#myselect').view(json);
}
});
See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown
在此处查看详细信息:https: //jocapc.github.io/jquery-view-engine/docs/ajax-dropdown
回答by Michael Bobis
zeusstl is right. it works for me too.
zeusstl 是对的。它也适用于我。
<select class="form-control select2" id="myselect">
<option disabled="disabled" selected></option>
<option>Male</option>
<option>Female</option>
</select>
$.getJSON("mysite/json1.php", function(json){
$('#myselect').empty();
$('#myselect').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
回答by Aithos
I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:
我知道这个问题有点老,但我会使用 jQuery 模板和 $.ajax 调用:
ASPX:
<select id="mySelect" name="mySelect>
<option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
<option value="${CityId}">${CityName}</option>
</script>
JS:
$.ajax({
url: location.pathname + '/GetCities',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
$('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect');
}
});
In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.
除了上述内容之外,您还需要一个 Web 方法 (GetCities),它返回一个对象列表,其中包含您在模板中使用的数据元素。我经常使用实体框架,我的 web 方法将调用一个管理器类,该类使用 linq 从数据库中获取值。通过这样做,您可以将输入保存到数据库中,刷新选择列表就像在保存成功时调用 JS 中的数据绑定一样简单。