【发布时间】:2011-06-28 17:15:41
【问题描述】:
我有一个地图对象,我在控制器中的 Spring ModelAndView 中放置并转发到我的 jsp 视图以填充选择。在它第一次填充之后,我想用我正在使用 jquery AJAX 检索并使用 jQuery.parseJSON 转换为对象的 json 对象替换用于填充选择的地图对象。可以用json对象的内容动态替换select的全部内容吗?
【问题讨论】:
我有一个地图对象,我在控制器中的 Spring ModelAndView 中放置并转发到我的 jsp 视图以填充选择。在它第一次填充之后,我想用我正在使用 jquery AJAX 检索并使用 jQuery.parseJSON 转换为对象的 json 对象替换用于填充选择的地图对象。可以用json对象的内容动态替换select的全部内容吗?
【问题讨论】:
$.ajax({
type: 'POST',
url: getpolicytypeUrl ,
data: { sirket: companyname },
success: function (data) {
$.each(data, function(index, element) {
$('#policyshortname').append($('<option>', {
text: element.policyShortname
}));
$('#policyshortname').show(300);
});
}
});
$('#policyshortname').html('refresh',true);
【讨论】:
对于实际修改选项,您并不需要 jQuery。您可以通过分配给SELECT 框的options 属性的length 属性来清除旧选项,然后通过#add 和new Option() 添加新选项。
这里有几个使用 jQuery 作为 XHR 部分的示例,然后直接执行选项:
如果您从对象内的数组中绘制数据(在这种情况下,是由结果对象上的属性options 标识的数组):
JSON:
{
"options": [
{"value": "New1", "text": "New Option 1"},
{"value": "New2", "text": "New Option 2"},
{"value": "New3", "text": "New Option 3"}
]
}
JavaScript:
$.ajax({
url: "http://jsbin.com/apici3",
dataType: "json",
success: function(data) {
var options, index, select, option;
// Get the raw DOM object for the select box
select = document.getElementById('theSelect');
// Clear the old options
select.options.length = 0;
// Load the new options
options = data.options; // Or whatever source information you're working with
for (index = 0; index < options.length; ++index) {
option = options[index];
select.options.add(new Option(option.text, option.value));
}
}
});
如果您将对象的属性名称用作option 值,并将属性值用作选项文本:
JSON:
{
"new1": "New Option 1",
"new2": "New Option 2",
"new3": "New Option 3"
}
JavaScript:
$.ajax({
url: "http://jsbin.com/apici3/2",
dataType: "json",
success: function(data) {
var name, select, option;
// Get the raw DOM object for the select box
select = document.getElementById('theSelect');
// Clear the old options
select.options.length = 0;
// Load the new options
for (name in data) {
if (data.hasOwnProperty(name)) {
select.options.add(new Option(data[name], name));
}
}
}
});
更新:而不是
select.options.add(new Option(...));
你也可以这样做:
select.options[select.options.length] = new Option(...);
...我认为实际上我倾向于在options 类似数组的东西上使用add 方法(我没有将其称为数组,因为它有一个方法add,数组没有;因为如果你使用push,数组确实有,它就不起作用)。
我已经测试了这两种方法
...两者都有效。也许有 Mac 的人可以帮我在 OS X 上试用 Safari。
我想说这两种方式都得到了非常非常好的支持。
【讨论】:
options 属性不(只是)一个数组,它有一个add 方法(参见我的代码)(再次)适用于所有主流浏览器。 (请注意,我在 options 上使用 add,而不是在 select 元素本身上。)你说得对,appendChild 确实 not 可靠地工作,这就是为什么我'我不使用它。 Tim 通过select.options[select.options.length] = new Option(...); 添加的方法也适用于所有主流浏览器。