jQuery jquery用json数据填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5952284/
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
jquery fill dropdown with json data
提问by user373201
I have the following jQuery code. I am able to get the following data from server [{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]
. How do I iterate over this and fill a select box with id=combobox
我有以下 jQuery 代码。我能够从服务器获取以下数据[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]
。我如何迭代这个并填充一个选择框id=combobox
$.ajax({
type: 'POST',
url: "<s:url value="/ajaxMethod.action"/>",
data:$("#locid").serialize(),
success: function(data) {
alert(data.msg);
//NEED TO ITERATE data.msg AND FILL A DROP DOWN
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
dataType: "json"
});
Also what is the difference between using .ajax
and $.getJSON
.
还有 using.ajax
和$.getJSON
.
回答by namuol
This should do the trick:
这应该可以解决问题:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
这是ajax
和getJSON
(来自jQuery 文档)之间的区别:
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
[getJSON] 是 Ajax 函数的简写,相当于:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
编辑:要清楚,部分问题是服务器的响应返回了一个如下所示的 json 对象:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
...因此该msg
属性需要使用$.parseJSON()
.
回答by Tejs
If your data is already in array form, it's really simple using jQuery:
如果您的数据已经是数组形式,那么使用 jQuery 真的很简单:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
.ajax()
比.getJSON()
-更灵活- 一方面,getJson 专门针对检索 json 的 GET 请求;ajax() 可以请求任何动词以取回任何内容类型(尽管有时这没有用)。getJSON 在内部调用 .ajax()。
回答by sumit pardeshi
Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/
URL. Upon success, it removes all items from dropdown list with id
= OfferTransModel_ItemID
and then it fills it with new items based on AJAX call's result:
这是一个代码示例,它尝试从/Ajax/_AjaxGetItemListHelp/
URL获取 AJAX 数据。成功后,它使用id
=从下拉列表中删除所有项目OfferTransModel_ItemID
,然后根据 AJAX 调用的结果用新项目填充它:
if (productgrpid != 0) {
$.ajax({
type: "POST",
url: "/Ajax/_AjaxGetItemListHelp/",
data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
contentType: "application/json",
dataType: "json",
success: function (data) {
$("#OfferTransModel_ItemID").empty();
$.each(data, function () {
$("#OfferTransModel_ItemID").append($("<option>
</option>").val(this['ITEMID']).html(this['ITEMDESC']));
});
}
});
}
Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID
and ITEMDESC
elements. For example:
返回的 AJAX 结果应返回编码为 AJAX 数组的数据,其中每个项目包含ITEMID
和ITEMDESC
元素。例如:
{
{
"ITEMID":"13",
"ITEMDESC":"About"
},
{
"ITEMID":"21",
"ITEMDESC":"Contact"
}
}
The OfferTransModel_ItemID
listbox is populated with above data and its code should look like:
该OfferTransModel_ItemID
列表框填充了上述数据和代码应该是这样的:
<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
<option value="13">About</option>
<option value="21">Contact</option>
</select>
When user selects About
, form submits 13
as value for this field and 21
when user selects Contact
and so on.
当用户选择时About
,表单13
作为该字段的值提交,21
当用户选择时Contact
,依此类推。
Fell free to modify above code if your server returns URL in a different format.
如果您的服务器以不同的格式返回 URL,可以随意修改上面的代码。
回答by NewBie
In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)
在大多数公司中,他们需要所有页面的多个下拉列表的通用功能。只需调用函数或传递您的 (DropDownID,JsonData,KeyValue,textValue)
<script>
$(document).ready(function(){
GetData('DLState',data,'stateid','statename');
});
var data = [{"stateid" : "1","statename" : "Mumbai"},
{"stateid" : "2","statename" : "Panjab"},
{"stateid" : "3","statename" : "Pune"},
{"stateid" : "4","statename" : "Nagpur"},
{"stateid" : "5","statename" : "kanpur"}];
var Did=document.getElementById("DLState");
function GetData(Did,data,valkey,textkey){
var str= "";
for (var i = 0; i <data.length ; i++){
console.log(data);
str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";
}
$("#"+Did).append(str);
}; </script>
</head>
<body>
<select id="DLState">
</select>
</body>
</html>