添加新条目后更新选择框

时间:2015-11-29 17:10:38

标签: javascript jquery jsp drop-down-menu

我有两个jsp页面add.jsp和view.jsp。有一个下拉列表,其中包含视图页面上的所有用户ID,当页面加载时,我将自动从数据库中提取这些用户ID(我使用document.ready事件来检索值)。

当我在add.jsp页面上添加新用户并单击“提交”时,它将重定向到带有成功消息的view.jsp页面。但是,下拉列表不会显示添加的新用户标识。我必须关闭并重新运行该项目,以便下次出现。

如何使用新添加的用户附加选择框?

    view.jsp

<script>

$(document).ready(function() {
    $.get('MyController', function(response){
        var $select = $(#myselect);
        $.each(response,function(key,value){
            $('<option>').val(key).text(value).appendTo($select);
        });
    });
});
</script>
..
..
..
<body><form>
<select id=myselect></select>
</form>
</body></html>

Mycontroller.java

doGet (HttpServletRequest req, HttpServletResponse res){
//construct json object
//write to response

}

doPost (HttpServletRequest req, HttpServletResponse res){
//adduser to DB
//return userId generated
/*send the generated id to view.jsp page*/

RequestDispatcher rd = req.getRequestDispatcher("view.jsp");
req.setattribute("generatedId",id);
rd.forward(req,res);
}


The generated Id is sent to view.jsp page. I want to append this new id to the select box in view page along with the existing id's
(which were already loaded using javascript).

1 个答案:

答案 0 :(得分:0)

由于您在页面加载时从数据库中获取vales,因此您的下拉列表将不会被更新,直到页面重新加载..如果想要更新而不需要刷新您需要做的是从文本框中获取提交点击的用户ID您需要附加如果数据库生成的userid在ajax成功时从控制器返回更新数据,则将其下拉到下拉列表

var newOption = $('<option value="'+yournewvalue+'">'+yournewvalue+'</option>');
 $('#yourdropdownid').append(newOption);
相关问题