如何使用servlet响应填充下拉值

时间:2014-06-08 16:58:01

标签: java jquery html jsp servlets

我能够从servlet获得响应,并且能够在jsp页面上显示它,但是如果我尝试在下拉列表中填充它,我无法 -

Servlet代码

String sql = "SELECT records from department";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();

while (rs.next()) {
  options.put(rs.getString("records"),rs.getString("records"));
}
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

JSP代码 ---

JS代码

<script type="text/javascript">
$(document).ready(function () {                           // When the HTML DOM is ready loading, then execute the following function...
    $('.btn-click').click(function () {                  // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
        $.get('/testservlet', function (responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
            //alert(responseJson);
            var $select = $('#maindiv');                           // Locate HTML DOM element with ID "someselect".
            $select.find('option').remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
            $.each(responseJson, function (key, value) {               // Iterate over the JSON object.
                $('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
            });
        });
    });
});
</script>

HTML代码 -

<input type="button" class="btn-click" id="best" value="check"/>
<div id="maindiv" style="display: block"></div>

如果我创建<ul><li>我可以在我的网页上获得响应中的数据,但无法创建选择选项吗?对此的任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

删除开头/后再试一次。

$.get('testservlet', function (responseJson)

JSON字符串不正确。它应该是this之类的东西。为什么你在这里使用JSON字符串,而你只传递记录作为键和值。

只需从Servlet返回一个逗号分隔的字符串并将其拆分为jQuery。

在此处查找Iterating a comma separated string

的示例

示例代码:

var items = responseJson.split(',');

for ( var i = 0; i < items.length; i++) {
    $('<option>').val(items[i]).text(items[i]).appendTo($select); 
}