In this example, I use jQuery, and the jQuery plugin jQuery - Select box manipulation, JSONObject, and the basic Java Servlet.
In web.xml, add these period of codes.
HelloServlet
HelloServlet
HelloServlet
/Hello
About the JSP file, remember to make the encoding consistent with the servlet.
And we have to include two javascript files, "jquery-1.2.6.min.js" and "jquery.selectboxes.pack.js". Please ignore the ".".
<%@ page language="java" pageEncoding="UTF-8"%>
< html>
< head>
< title>Dynamic double combo< /title>
< meta http-equiv=content-type content="text/html; charset=UTF-8">
< script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.3.2.min.js">< /script>
< script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.selectboxes.pack.js">< /script>
< script type="text/javascript">
$(document).ready(function(){
$("#select1").change(function(){
$("#select2").empty();
$("#select2").addOption("0","------");
$("#select2").ajaxAddOption("<%=request.getContextPath()%>/Hello",
{selVal:$("select[name='select1'] option[selected]").val()},false);
});
});
< /script>
< /head>
< body>
< select id="select1" name="select1">
< option value="A">A< /option>
< option value="B">B< /option>
< option value="C">C< /option>
< /select>
< select id="select2" name="select2">
< option value="0"> --- < /option>
< /select>
< /body>
< /html>
HelloServlet.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
public class HelloServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
try{
String val = request.getParameter("selVal");
JSONObject obj = new JSONObject();
if(val.equals("A")){
obj.put("A-1", "A-1");
}else if(val.equals("B")){
obj.put("B-1", "B-1");
}else if(val.equals("C")){
obj.put("C-1", "C-1");
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(obj.toString());
return;
}catch(Exception e){
e.printStackTrace();
}
}
}
沒有留言:
張貼留言