在Spring MVC环境中使用查询用ajax调用的结果填充列表框选项。
问题内容:
目前,我正在进行第一个jquery /
ajax调用,并且在如何将服务器端结果填充到列表框中时遇到问题。spring控制器正确(希望)向我返回了数据,但jquery部分在填充列表框时才遇到问题。
这是我的ajax电话
$(function() {
$projectKey = $('#projectKey');
$projectKey.change (
function() {
$.ajax({
type: "GET",
url: "getVersionsByProjectKey",
data: {"projectKey": $projectKey.val() },
dataType: 'json',
success: function(data){
alert('success');
alert(data);
$('#jiraVersion').append(
$('<option></option>').html(data)
);
}
});
}
);
});
这是我的 控制器的 外观:
@RequestMapping(value="/getVersionsByProjectKey", method = RequestMethod.GET)
public @ResponseBody List<String> getVersionsByProjectKey(@RequestParam(value = "projectKey") String projectKey) {
List<String> versions = new ArrayList<String>();
versions.add("Chuck");
versions.add("Norris");
versions.add("John");
versions.add("Doe");
return versions;
}
这是我要填充数据的列表框:
<td>
<form:select path="jiraVersion" id="jiraVersion">
</form:select>
</td>
正如我之前所说,我现在只是熟悉jquery,并尝试了google的几种解决方案,但没有任何乐趣。我试过了:
success: function(data){
alert('success');
alert(data);
$.each(data, function(index, item) {
$("#jiraVersion").get(0).options[$("#jiraVersion").get(0).options.length] =
new Option(item.Display, item.Value);
});}
等等等
警报(“成功”)写道:Chuck,Norris,John,Doe
。
如果我直接发送请求 /getVersionsByProjectKey?projectKey=AIL
我回来了 ["Chuck","Norris","John","Doe"]
而且我还尝试将修改success
为:
success: function(data){
alert('success');
alert(data);
$('#jiraVersion').append(
$('<option></option>').html(data)
);
}
然后我的列表框仅包含一个选项 ChuckNorrisJohnDoe 。知道我在做什么错吗?
问题答案:
由于data
来自Ajax调用的是数组["Chuck","Norris","John","Doe"]
,因此您需要使用jQuery.each()
以下命令进行迭代:
将此功能用作success
:
success: function(data){
$.each(data, function(index, value) {
$('#jiraVersion').append($('<option>').text(value).val(index));
});
}
这将附加/生成:
<form:select path="jiraVersion" id="jiraVersion">
<option value="0">Chuck</option>
<option value="1">Norris</option>
<option value="2">John</option>
<option value="3">Doe</option>
</form:select>