Spring <form:select>元素的AJAX更新

Ron*_*ael 0 ajax jsp spring-mvc auto-update

我正在使用Spring MVC进行项目.在其中,在特定页面上,我使用Spring表单标签来显示添加到控制器中模型的ArrayList,如下所示:

<form:select path="myList">
    <form:options items="${listElements}"/>
</form:select>
Run Code Online (Sandbox Code Playgroud)

现在,listElements可以从另一个页面(子窗口)编辑,所以我希望myList每2秒左右自动更新一次.截至目前,我在添加元素时刷新父窗口; 但是,父页面中的表单还有其他字段,用户只需键入数据,因此完全刷新会重置该数据,因为它尚未发布.因此,我想使用AJAX form:select每2秒更新一次我的元素.

我怎样才能做到这一点?

注意:我是一个AJAX菜鸟.我在SO和其他地方经历了一些类似的帖子,但遗憾的是我无法弄明白.任何帮助将非常感谢!

小智 6

1.在select元素中添加Id属性.

2.在mvc控制器中添加ajax方法处理程序,返回arrayList(我更喜欢返回json对象).

3.在jquery/javascript中激活ajax调用

JSP代码:

<head>
    <link href="<c:url value="/resources/form.css" />" rel="stylesheet"  type="text/css" />
    <script type="text/javascript" src="<c:url value="/resources/jquery/1.6/jquery.js" />"></script>
        <script type="text/javascript">
        var interval =2000;
        setInterval("getServerData()",interval);
        function getServerData(){
            $.getJSON("/MyApp/data/jsonList", function(response){ 
                $("#selectBox option").remove(); 
                    var options = '';
                    $.each(response, function(index, item) {
                        options += '<option value="' + item + '">' + item + '</option>';
                        $("#selectBox").html(options);
                    });
            });
        }
        </script>           
</head>
<body>
    <form:form id="form" method="post">
        <select id="selectBox">
        <select>
    </form:form>    
</body>
Run Code Online (Sandbox Code Playgroud)

控制器代码:

@RequestMapping(value="/data/jsonList", method=RequestMethod.GET)
public @ResponseBody List<String> getDataList() {
    List<String> myList = new ArrayList<String>();
    myList.add("option1");
    myList.add("option2");
    myList.add("option3");
    myList.add("option4");
    return myList;
}
Run Code Online (Sandbox Code Playgroud)

如果你打算用户jquery检查 通过jQuery AJAX更新选择框选项?

好读:Spring ajax 3.0页面.