2014-06-12 4 views
0

에 데이터베이스에서 드롭 다운 목록을 채우는JSP이 내 코드 버튼을 클릭

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
       <title>JSP Page</title> 
      </head> 
      <body> 
       <sql:setDataSource var="db" 
            driver="com.mysql.jdbc.Driver" 
            url="jdbc:mysql://localhost/dbase" 
            user="root" 
            password="1asulxayev" /> 
       <sql:query var="select" dataSource="${db}"> 
        select * from dtable 
       </sql:query> 
        <select name="lst"> 
        <c:forEach var="result" items="${select.rows}"> 
         <option>${result.name}</option> 
        </c:forEach> 
       </select>  
       <input type="submit" value="Fill" name="btn"> 
       </body> 
     </html> 

이 시간 때 페이지로드 드롭 다운 목록 웁니다. 하지만 난 버튼을 클릭 채우기 드롭 다운 목록 여기

+0

는 많은 예 괜찮 –

+0

은 ... 온라인 ajax..there 있습니다 사용하여 않습니다. 하지만 난 examle 필요 – Beginner

답변

1

는 AJAX를 사용하여 샘플 코드 인 경우합니다. 더 많은 정보를 위해 인라인 주석을 참조하십시오.

서블릿 :

doGet() 방법으로 데이터베이스에서 데이터를 가져 오기 단순히 쉼표로 구분 된 문자열을 HTTP 응답을 작성하고 클라이언트로 세척합니다.

는 HTML :

<head> 
<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('myServletURL', 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). 
           var items = responseJson.split(','); 

           for (var i = 0; i < items.length; i++) { 
            $('<option>').val(items[i]).text(items[i]) 
              .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> 

</head> 
<body> 
    <select id="maindiv" style="width: 300px;"></select> 
    <input type="button" class="btn-click" id="best" value="check" /> 
</body>