jQuery使用JSON数据填充下拉列表 [英] jquery fill dropdown with json data
问题描述
我有以下jQuery代码.我可以从服务器[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]
中获取以下数据.如何对此进行迭代,并用id=combobox
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
$.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"
});
另外,使用.ajax
和$.getJSON
有什么区别.
Also what is the difference between using .ajax
and $.getJSON
.
推荐答案
这应该可以解决问题:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
这是ajax
和getJSON
之间的区别(来自 jQuery文档) :
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON]是Ajax的简写功能,等效于:
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
要清楚,部分问题是服务器的响应正在返回一个看起来像这样的json对象:
To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...因此需要使用$.parseJSON()
手动解析msg
属性.
...So that msg
property needed to be parsed manually using $.parseJSON()
.
这篇关于jQuery使用JSON数据填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!