三、创建Jsp页面:
<%@ page language="java" pageEncoding="gbk"%>
<%@ page import="java.util.*"%>
<%@ page import="com.core.*"%>
<%@ page import="java.sql.*" %>
<%
//获取参数
String times = (request.getParameter("para") == null )? "" : request.getParameter("para") ;
List<Integer> timesColl = new ArrayList<Integer>();
try{
ConnDB conn = new ConnDB() ;
//当用户传递过来参数不为空时,向数据库插入数据
if(!times.equals("")){
String sql = "insert into times values('"+times+"')" ;
//测试
System.out.println("sql-------->"+sql) ;
conn.executeUpdate(sql);
}
String sql = "select ti from times" ;
ResultSet rs = conn.executeQuery(sql) ;
while(rs.next()){
timesColl.add(rs.getInt(1));
}
// 捕获异常
}catch(Exception e){
e.printStackTrace() ;
}
%>
<html>
<head>
<title>下拉列表+Javascript</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form name = "form1" action="index.jsp" method="post" />
频率:
<select name="pl" id="pl" style="width:45px" >
<!—动态加载下拉列表的值-->
<%for(int i:timesColl){ %>
<option value="<%=i %>"><%=i %></option>
<%} %>
</select>
<input type="text" size="10" name="times" id="times"> <input type="button" name="b1" id="b1" value="添加" onclick="addtimes();">
</form>
<script type="text/javascript">
function addtimes(){
alert("ok") ;
//form对象
var f = document.getElementById("form1") ;
//获取文本值
var v = document.getElementById("times").value ;
//select对象
var sObject = document.getElementById("pl") ;
alert(v) ;
//先判断下拉列表是否已经存在该值
var len = sObject.options.length;
alert("select长度--"+len) ;
var flag = false ;
for(var i=0;i<len;i++){
if(v==sObject.options[i].value){
alert("存在该值!") ;
flag = true ;
//退出循环
break ;
}
}
//当文本框的值与要添加的值不相等时,才向更新数据库
if(flag==false){
f.action="index.jsp?para="+v ;
f.submit() ;
}
}
</script>
</body>
</html>