关于ajax 调用数据库局部更新页面数据

首先前端页面的触发事件引发ajax事件:
起那段页面如下:
<%@page language="java" import="java.util.*" pageEncoding="gb2312"%>
<META http-equiv=Content-Type content="text/xml;charset = gbk" pageEncoding = "gbk">
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/sm/";
%>
<html>
    <head>
<base href="<%=basePath%>">
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>商品类别管理</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<link href="../resources/css/hottest.css" rel="stylesheet" type="text/css" />
<style type="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>
<script type="text/javascript">
    function checkName(){
var x=document.getElementById("categoryName");
if(x.value==""){
    document.getElementById("nameErr").innerHTML="<img src='../resources/images/no.gif' width='16' height='16' />商品名不能为空!";
    return false;
}
else{
    document.getElementById("nameErr").innerHTML="<img src='../resources/images/yes.gif' width='16' height='16' />";
    return true;
}
    }
    function checkT(stateVal){
var url = "${pageContext.request.contextPath}/CategoryajaxServlet.do?tlevel="+document.getElementById("tlevel").value;
if(document.getElementById("tlevel").value.toString()=="3"){
    var a=document.getElementById("parentCategory");
    document.getElementById("parentCategory").removeChild(a.options[0]);
    if (window.XMLHttpRequest)
    {
req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
req = new ActiveXObject("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="<option value=所有商品>所有商品</option>";
}
    }
    function complete()
    {
var parentCategory=document.getElementById("parentCategory");

if (req.readyState == 4)
{
    if (req.status == 200)
    {
document.getElementById("parentCategory").innerHTML= req.responseText;
    }
}

    }
</script>
    </head>
    <body>
<form action="<%=path%>/AddCategoryServlet.do" method="post">
    <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="30"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="15" height="30"><img src="../resources/images/tab_03.gif" width="15" height="30" /></td>
<td background="../resources/images/tab_05.gif" align="left"><img src="../resources/images/311.gif" width="16" height="16" /> <span class="STYLE4">商品类别添加</span></td>
<td width="14"><img src="../resources/images/tab_07.gif" width="14" height="30" /></td>
</tr>
    </table></td>
    </tr>
    <tr>
    <td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="15" style="background:url(../resources/images/tab_12.gif) repeat-y left #d3e7fc; "></td>
    <td width="97%" bgcolor="#FFFFFF" height="500" valign="top" align="center" style="padding-top:20px;">
<table width="505px" border="0" cellspacing="0" cellpadding="0">
    <tr style="width:100%;height:20px;background:url(../resources/images/htbg1.gif);">
    <td></td>
    </tr>
    <tr style="width:100%; height:250px; background: url(../resources/images/htbg3.gif) repeat-y; text-align:center;">
    <td>
<table width="80%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="20%" height="40" align="right" class="STYLE4">类别名称:</td>
    <td align="left"><input type="text" name="categoryName" id="categoryName" onblur="checkName()"/><span id="nameErr"></span></td>
    </tr>
    <tr>
    <td height="40" align="right" class="STYLE4">类别层次:</td>
    <td height="30" align="left">
<select name="tlevel" id="tlevel" onblur="checkT()">
    <option value="2">2</option>
    <option value="3">3</option>
</select>
    <span id="tlevelErr"></span>
    </td>
    </tr>
    <tr>
    <td height="40" align="right" class="STYLE4">父&nbsp;&nbsp;&nbsp;&nbsp;类:</td>
    <td height="30" align="left">
<select name="parentCategory" id="parentCategory" >
    <option value="所有商品">所有商品</option>
</select>
    </td>
    </tr>
    <tr>
    <td height="40" align="right" class="STYLE4">状&nbsp;&nbsp;&nbsp;&nbsp;态:</td>
    <td height="30" align="left">
<select name="status"> <option value="激活">激活</option><option value="冻结">冻结</option></select></td>
    </tr>
    <tr>
    <td height="40" colspan="2" align="center">
<input type="submit" value="确定"  class="bt_01"/>&nbsp;
<input type="reset" value="取消"  class="bt_01"/></td>
    </tr>
    <tr><td height="40" colspan="2" align="center" class="STYLE4"><span id="prompt">${result}</spen></td>
</tr>
</table>
    </td>
</tr>
<tr style="width:100%; height:17px; background: url(../resources/images/htbg2.gif) no-repeat;">
<td>&nbsp;</td>
</tr>
</table>
</td>
<td width="14"  style="background:url(../resources/images/tab_16.gif) repeat-y right #d3e7fc; ">&nbsp;</td>
</tr>

</table>

</td>
</tr>
<tr>
<td height="29"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
        <td width="15" height="29"><img src="../resources/images/tab_20.gif" width="15" height="29" /></td>
        <td background="../resources/images/tab_21.gif"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="21%" height="14">&nbsp;</td>
<td width="79%" class="STYLE1" align="right">&nbsp;</td>
</tr>
    </table></td>
        <td width="14"><img src="../resources/images/tab_22.gif" width="14" height="29" /></td>
</tr>
    </table></td>
</tr>
</table>
</form>
</body>
</html>

根据select的变化局部更新<option>的内容

后台ajax的读取数据的代码如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fyz.servlet.ajax;

import com.fyz.factory.DAOFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author RDGFT
*/
@WebServlet(name = "CategoryajaxServlet", urlPatterns = {"/CategoryajaxServlet"})
public class CategoryajaxServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
StringBuffer string = new StringBuffer();
String s=null;
try {
    /* TODO output your page here. You may use following sample code. */
    List list = DAOFactory.getCategoryDAOIMP().queryCategory_name(2);
    Iterator it = list.iterator();
    while (it.hasNext()) {
s=(String) it.next();
string.append("<option value="+s+">"+s+"</option>");
    }
    out.write(string.toString());
} finally {
    out.close();
}
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
processRequest(request, response);
    }

 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
processRequest(request, response);
    }

 
    public String getServletInfo() {
return "Short description";
    }
}


提交表单的数据代码如下;


package com.fyz.servlet_sm;

import com.fyz.vo.CategoryVO;
import com.fyz.factory.DAOFactory;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AddCategoryServlet extends HttpServlet {
    //doGet

    Random random;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
CategoryVO cvo = new CategoryVO();
//从前台表单获得数据并存入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", "添加商品分类失败!");
}
//页面跳转
RequestDispatcher rd = request.getRequestDispatcher("sm/addCategory.jsp");
rd.forward(request, response);
    }

    //doPost()
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
doGet(request, response);
    }
}


调用数据库部分代码如下:

public boolean addCategory(CategoryVO cvo) {
boolean result = false;
Connection conn = null;
PreparedStatement ps = null;
CallableStatement csmt = null;
ResultSet rs = null;
try {
    conn = DBUtil.getInstance().getConn();
    csmt = conn.prepareCall("{call add_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());
    int i=csmt.executeUpdate();
    if (i>=0) {
result = true;
    }
} catch (Exception ex) {
    Logger.getLogger(CategoryDAOIMP.class.getName()).log(Level.SEVERE, null, ex);
} finally {
    DBUtil.dbClose(ps, conn);
}

return result;
    }



希望能给你带来收获

猜你喜欢

转载自fengyanzhang.iteye.com/blog/1882918