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>
我可以從我的網頁上的反應數據,但不能創建選擇選項?任何對此的幫助都會很大。
感謝Braj。但是我遵循[來自這裏]的BalusC建議(http://stackoverflow.com/a/4113258/2480307)。它也應該像地圖案一樣工作,就像我正在做的那樣? – AKIWEB
你必須修改你的JSON字符串。我與你分享了一些鏈接。你看過任何一個。 – Braj
是的,這是另一種方式做下面這樣做:)感謝分享 – AKIWEB