jQuery 如何将 json 结果正确附加到选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16160619/
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 to properly append json result to a select option
提问by SHINHAN
How to properly append json result to a select option,
如何将 json 结果正确附加到选择选项,
sample json data
示例 json 数据
Ajax code:
阿贾克斯代码:
$.ajax({
url: 'sessions.php',
type: 'post',
datatype: 'json',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
sucess: function(data){
var toAppend = '';
//if(typeof data === 'object'){
for(var i=0;i<data.length;i++){
toAppend += '<option>'+data[i]['id']+'</option>';
}
//}
$('#sessions').append(toAppend);
}
});
html code:
html代码:
<p>Sessions:
<select id="sessions"></select>
I already set to my php file
我已经设置为我的 php 文件
header("Content-Type: application/json");
回答by PSL
Use $.eachto iterate through your JSON array that you receive from ajax call.
使用$.each通过您的JSON数组进行迭代,你从AJAX调用接收。
Note:- the spelling of success
, you have written sucess
.
注意:- 的拼写success
,你已经写了sucess
。
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>';
});
$('#sessions').append(toAppend);
}
You can do append to the DOM directly inside the each loop but it is always better to concatenate with string and then adding to the DOM later. This is a cheaper operation since you are accessing DOM only once in this case. This might not work in some complex scenarios though.
您可以直接在 each 循环内追加到 DOM,但最好与字符串连接,然后再添加到 DOM。这是一种成本较低的操作,因为在这种情况下您只访问 DOM 一次。不过,这在一些复杂的场景中可能不起作用。
回答by khem raj regmi
success: function(data) {
var options = "";
for (var i = 0; i < data.length; i++) {
options += "<option>" + data[i].id + "</option>";
}
$("#sessions").html(options);
}
If your response is in multidimensional array then try as follows
如果您的响应在多维数组中,请尝试如下
success: function(data) {
var options = '';
for (var i = 0; i < data.length; i++) {
for (var j = 0; j< data[i].length; j++){
options += '<option value="' + data[i][j].product_id + '">' + data[i][j].name + '</option>';
}
}
$("#products").html(options);
}
回答by gks
I hope this will help you to append
我希望这会帮助你追加
for(i=0; i<data.length; i++) {
$('#sessions').append("<option value="+data[i].id+"/option>");
}
回答by hitesh bariya
Please try the below code this may help you.
请尝试以下代码,这可能对您有所帮助。
these code i used in spring boot MVC
我在 Spring Boot MVC 中使用的这些代码
JSON Data
JSON 数据
[{"name":"Afghanistan","code":"af"},
{"name":"Albania","code":"al"},
{"name":"Algeria","code":"dz"}]
JQuery Code
查询代码
var jsonData = '${restData}';
var obj = JSON.parse(jsonData);
for (i in obj) {
$('#selectList').append(new Option(obj[i].name, obj[i].code));
}