我有一个 map 对象,我将其放置在 Controller 中的 Spring ModelAndView
中,并转发到我的 jsp View 以填充选择。在它第一次填充之后,我想用我使用 jquery AJAX 检索并使用 jQuery.parseJSON 转换为对象的 json 对象替换用于填充选择的 map 对象。可以用json对象的内容动态替换select的全部内容吗?
最佳答案
对于实际修改选项,您并不需要 jQuery。您可以通过分配给 length
来清除旧选项。 options
的属性(property)SELECT
的属性(property)框,然后通过 #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(...);
...我认为实际上我倾向于使用 add
options
上的方法类似数组的东西(我不是称它为数组,因为它有一个方法 add
,而数组没有;而且因为如果你使用 push
,哪些数组做有,它不起作用)。
我已经测试了这两种方法
- IE6、7、8(Windows)
- Chrome(Linux 和 Windows)
- 火狐(Linux 和 Windows)
- Opera(Linux 和 Windows)
- Safari (Windows)
...两者都有效。也许有 Mac 的人可以帮我在 OS X 上试用 Safari。
我想说这两种方式都得到了非常非常好的支持。
关于jquery - 您如何使用 jquery 更新选择的所有选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5022928/