AKIWEB
AKIWEB

Reputation: 19612

How to populate drop down values using servlet response

I am able to have the response from a servlet and also able to show it on jsp page, but if I try to populate the same in a drop down, i am not able to-

Servlet code

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 code---

JS code

<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 Code--

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

If I create a <ul> and <li> I can have the data from the response on my page but not able to create the select options? Any help on this would be great.

Upvotes: 1

Views: 6920

Answers (1)

Braj
Braj

Reputation: 46841

Try it again after removing beginning /.

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

The JSON string is not in proper way. It should be something like this. Why are you using JSON string here whereas you are passing only records as key as well as value.

Simply return a comma separated string from Servlet and split it jQuery.

Find example here for Iterating a comma separated string

Sample code:

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

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

Upvotes: 1

Related Questions