关于ajax 调用数据库局部更新页面数据
首先前端页面的触发事件引发ajax事件:
起那段页面如下:
<%@pagelanguage="java"import="java.util.*"pageEncoding="gb2312"%>
<METAhttp-equiv=Content-Typecontent="text/xml;charset=gbk"pageEncoding="gbk">
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/sm/";
%>
<html>
<head>
<basehref="<%=basePath%>">
<metahttp-equiv="content-type"content="text/html;charset=gb2312">
<title>商品类别管理</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<linkhref="../resources/css/hottest.css"rel="stylesheet"type="text/css"/>
<styletype="text/css">
<!--
body{
margin-left:0px;
margin-top:0px;
margin-right:0px;
margin-bottom:0px;
}
.STYLE1{font-size:12px}
.STYLE4{
font-size:12px;
color:#1F4A65;
font-weight:bold;
font-family:"宋体";
}
a:link{
font-size:12px;
color:#06482a;
text-decoration:none;
}
a:visited{
font-size:12px;
color:#06482a;
text-decoration:none;
}
a:hover{
font-size:12px;
color:#FF0000;
text-decoration:underline;
}
a:active{
font-size:12px;
color:#FF0000;
text-decoration:none;
}
.bt_01{
width:71px;
height:25px;
border:0px;
background:url(../resources/images/htdl.gif)no-repeat;
color:#fff;
font-size:12px;
}
-->
</style>
<scripttype="text/javascript">
functioncheckName(){
varx=document.getElementById("categoryName");
if(x.value==""){
document.getElementById("nameErr").innerHTML="<imgsrc='../resources/images/no.gif'width='16'height='16'/>商品名不能为空!";
returnfalse;
}
else{
document.getElementById("nameErr").innerHTML="<imgsrc='../resources/images/yes.gif'width='16'height='16'/>";
returntrue;
}
}
functioncheckT(stateVal){
varurl="${pageContext.request.contextPath}/CategoryajaxServlet.do?tlevel="+document.getElementById("tlevel").value;
if(document.getElementById("tlevel").value.toString()=="3"){
vara=document.getElementById("parentCategory");
document.getElementById("parentCategory").removeChild(a.options[0]);
if(window.XMLHttpRequest)
{
req=newXMLHttpRequest();
}
elseif(window.ActiveXObject)
{
req=newActiveXObject("Microsoft.XMLHTTP");
}
if(req)
{
//true:异步模式
req.open("GET",url,true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.onreadystatechange=complete;
req.send(null);
//document.getElementById("tlevelErr").innerText="请稍后,正在!";
}
}
else{
document.getElementById("parentCategory").innerHTML="<optionvalue=所有商品>所有商品</option>";
}
}
functioncomplete()
{
varparentCategory=document.getElementById("parentCategory");
if(req.readyState==4)
{
if(req.status==200)
{
document.getElementById("parentCategory").innerHTML=req.responseText;
}
}
}
</script>
</head>
<body>
<formaction="<%=path%>/AddCategoryServlet.do"method="post">
<tablewidth="100%"border="0"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdheight="30"><tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
<tr>
<tdwidth="15"height="30"><imgsrc="../resources/images/tab_03.gif"width="15"height="30"/></td>
<tdbackground="../resources/images/tab_05.gif"align="left"><imgsrc="../resources/images/311.gif"width="16"height="16"/><spanclass="STYLE4">商品类别添加</span></td>
<tdwidth="14"><imgsrc="../resources/images/tab_07.gif"width="14"height="30"/></td>
</tr>
</table></td>
</tr>
<tr>
<td>
<tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
<tr>
<tdwidth="15"style="background:url(../resources/images/tab_12.gif)repeat-yleft#d3e7fc;"></td>
<tdwidth="97%"bgcolor="#FFFFFF"height="500"valign="top"align="center"style="padding-top:20px;">
<tablewidth="505px"border="0"cellspacing="0"cellpadding="0">
<trstyle="width:100%;height:20px;background:url(../resources/images/htbg1.gif);">
<td></td>
</tr>
<trstyle="width:100%;height:250px;background:url(../resources/images/htbg3.gif)repeat-y;text-align:center;">
<td>
<tablewidth="80%"border="0"cellspacing="0"cellpadding="0">
<tr>
<tdwidth="20%"height="40"align="right"class="STYLE4">类别名称:</td>
<tdalign="left"><inputtype="text"name="categoryName"id="categoryName"onblur="checkName()"/><spanid="nameErr"></span></td>
</tr>
<tr>
<tdheight="40"align="right"class="STYLE4">类别层次:</td>
<tdheight="30"align="left">
<selectname="tlevel"id="tlevel"onblur="checkT()">
<optionvalue="2">2</option>
<optionvalue="3">3</option>
</select>
<spanid="tlevelErr"></span>
</td>
</tr>
<tr>
<tdheight="40"align="right"class="STYLE4">父 类:</td>
<tdheight="30"align="left">
<selectname="parentCategory"id="parentCategory">
<optionvalue="所有商品">所有商品</option>
</select>
</td>
</tr>
<tr>
<tdheight="40"align="right"class="STYLE4">状 态:</td>
<tdheight="30"align="left">
<selectname="status"><optionvalue="激活">激活</option><optionvalue="冻结">冻结</option></select></td>
</tr>
<tr>
<tdheight="40"colspan="2"align="center">
<inputtype="submit"value="确定"class="bt_01"/>
<inputtype="reset"value="取消"class="bt_01"/></td>
</tr>
<tr><tdheight="40"colspan="2"align="center"class="STYLE4"><spanid="prompt">${result}</spen></td>
</tr>
</table>
</td>
</tr>
<trstyle="width:100%;height:17px;background:url(../resources/images/htbg2.gif)no-repeat;">
<td> </td>
</tr>
</table>
</td>
<tdwidth="14"style="background:url(../resources/images/tab_16.gif)repeat-yright#d3e7fc;"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<tdheight="29"><tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
<tr>
<tdwidth="15"height="29"><imgsrc="../resources/images/tab_20.gif"width="15"height="29"/></td>
<tdbackground="../resources/images/tab_21.gif"><tablewidth="100%"border="0"cellspacing="0"cellpadding="0">
<tr>
<tdwidth="21%"height="14"> </td>
<tdwidth="79%"class="STYLE1"align="right"> </td>
</tr>
</table></td>
<tdwidth="14"><imgsrc="../resources/images/tab_22.gif"width="14"height="29"/></td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>
</html>
根据select的变化局部更新<option>的内容
后台ajax的读取数据的代码如下:
/*
*Tochangethistemplate,chooseTools|Templates
*andopenthetemplateintheeditor.
*/
packagecom.fyz.servlet.ajax;
importcom.fyz.factory.DAOFactory;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Iterator;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*
*@authorRDGFT
*/
@WebServlet(name="CategoryajaxServlet",urlPatterns={"/CategoryajaxServlet"})
publicclassCategoryajaxServletextendsHttpServlet{
/**
*ProcessesrequestsforbothHTTP
*<code>GET</code>and
*<code>POST</code>methods.
*
*@paramrequestservletrequest
*@paramresponseservletresponse
*@throwsServletExceptionifaservlet-specificerroroccurs
*@throwsIOExceptionifanI/Oerroroccurs
*/
protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriterout=response.getWriter();
StringBufferstring=newStringBuffer();
Strings=null;
try{
/*TODOoutputyourpagehere.Youmayusefollowingsamplecode.*/
Listlist=DAOFactory.getCategoryDAOIMP().queryCategory_name(2);
Iteratorit=list.iterator();
while(it.hasNext()){
s=(String)it.next();
string.append("<optionvalue="+s+">"+s+"</option>");
}
out.write(string.toString());
}finally{
out.close();
}
}
@Override
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
@Override
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
processRequest(request,response);
}
publicStringgetServletInfo(){
return"Shortdescription";
}
}
提交表单的数据代码如下;
packagecom.fyz.servlet_sm;
importcom.fyz.vo.CategoryVO;
importcom.fyz.factory.DAOFactory;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.util.Random;
importjava.util.logging.Level;
importjava.util.logging.Logger;
publicclassAddCategoryServletextendsHttpServlet{
//doGet
Randomrandom;
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsIOException,ServletException{
CategoryVOcvo=newCategoryVO();
//从前台表单获得数据并存入VO类中
cvo.setCate_name(request.getParameter("categoryName"));
cvo.setCate_layer(request.getParameter("tlevel"));
cvo.setCate_father(request.getParameter("parentCategory"));
cvo.setStatus(request.getParameter("status"));
//添加相应数据到数据库
if(DAOFactory.getCategoryDAOIMP().addCategory(cvo)){
request.setAttribute("result","添加商品分类成功!");
}else{
request.setAttribute("result","添加商品分类失败!");
}
//页面跳转
RequestDispatcherrd=request.getRequestDispatcher("sm/addCategory.jsp");
rd.forward(request,response);
}
//doPost()
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsIOException,ServletException{
doGet(request,response);
}
}
调用数据库部分代码如下:
publicbooleanaddCategory(CategoryVOcvo){
booleanresult=false;
Connectionconn=null;
PreparedStatementps=null;
CallableStatementcsmt=null;
ResultSetrs=null;
try{
conn=DBUtil.getInstance().getConn();
csmt=conn.prepareCall("{calladd_category(?,?,?,?)}");
System.out.println(cvo.getCate_name());
System.out.println(cvo.getCate_layer());
System.out.println(cvo.getCate_father());
System.out.println(cvo.getStatus());
csmt.setString(1,cvo.getCate_name());
csmt.setInt(2,Integer.parseInt(cvo.getCate_layer()));
csmt.setString(3,cvo.getCate_father());
csmt.setString(4,cvo.getStatus());
inti=csmt.executeUpdate();
if(i>=0){
result=true;
}
}catch(Exceptionex){
Logger.getLogger(CategoryDAOIMP.class.getName()).log(Level.SEVERE,null,ex);
}finally{
DBUtil.dbClose(ps,conn);
}
returnresult;
}
希望能给你带来收获
相关推荐
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo