2014-06-08 63 views
1

我能夠從servlet獲得響應,並且能夠在jsp頁面上顯示它,但是如果我嘗試在下拉列表中填充相同內容,我無法 -如何使用servlet響應填充下拉值

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

刪除開始/後再試一次。

$.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); 
} 
+0

感謝Braj。但是我遵循[來自這裏]的BalusC建議(http://stackoverflow.com/a/4113258/2480307)。它也應該像地圖案一樣工作,就像我正在做的那樣? – AKIWEB

+0

你必須修改你的JSON字符串。我與你分享了一些鏈接。你看過任何一個。 – Braj

+1

是的,這是另一種方式做下面這樣做:)感謝分享 – AKIWEB