AJAX update for Spring <form:select> 元素



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

<form:select path="myList">
    <form:options items="${listElements}"/>
</form:select>

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

我该怎么做?

注意:我是一个AJAX新手。我在SO和其他地方浏览了一些类似的帖子,但遗憾的是我没能弄清楚。任何帮助将非常感激!

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

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

3。jquery/javascript中的Fire 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>
控制器代码:

@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;
}

如果您计划使用jquery检查通过jQuery AJAX更新选择框选项?

我找到我要找的了!:)

为了防止将来有人发现它有用,我所做的如下:

  1. 给我的<form:select>一个id:

  2. 创建reloadlist.html,仅包含相关<form:select>的副本。

  3. 增加了以下脚本:

<script type="text/javascript">
function Ajax(){
var xmlHttp;
    try{    
        xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
    }catch (e){
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
        }catch (e){
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
                alert("No AJAX!?");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function(){
        document.getElementById('ReloadList').innerHTML=xmlHttp.responseText;
        setTimeout('Ajax()',10000);
    }
    xmlHttp.open("GET","reloadlist.html",true);
    xmlHttp.send(null);
}
window.onload=function(){
    setTimeout('Ajax()',10000);
}
</script>

这可能不是一个很好的方法来完成这个,但它工作。更好的答案将非常感激!

最新更新