`
_Yggd
  • 浏览: 86107 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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

    博客分类:
  • 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;
    }



希望能给你带来收获

分享到:
评论

相关推荐

    JQuery的Ajax请求实现局部刷新的简单实例

    请求的ajax路径传递的参数(data)会到action中被一个同样名字的变量(附带set get方法)接收,返回的data是一个JQuery的数组对象,在被调用的action中涉及到的数据变量会对象,都会封装到data中最终返回给页面。...

    PHP培训教程之AJAX技术.docx

    3、AJAX的特 Ajax可以实现动态不刷新(局部刷新) 就能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上那些没有改变过的信息。 4、XMLhttprequest对象。 Ajax的核心...

    AJAX基础概念、核心技术与典型案例(内涵动态实例)

    PostUser Ajax提交数据更新服务器内容 xmlhttpWeather 获取天气网站的内容 第11章(/C11/) 11.1.htm 采用标准的DOM方法创建一个表格并将其插入到页面中 11.2.htm 添加单元格 11.3....

    双鱼林PHP基于MVC三层模式图书管理系统 v1.0.rar

    系统前台架构技术: div css布局, ajax实现局部数据更新(采用Json数据格式传输) 系统开发工具用的是: Zend Studio集成环境 有代码提示 很方便!   系统开发环境: Windows Apache PHP Mysql   phpbean目录:...

    我的通讯录(PHP版)

    动态生成要执行的SQL语句.(System.PHp) (3).JS写成类,运用AJAX框架prototype.js局部更新页面信息,减少客户端等待.验证客户端数据时运用JS正则表达式 (4).封装操作类. 将用到的操作写成一个类,当运行出错时...

    ThinkPHP结合ajax、Mysql实现的客户端通信功能代码示例

    1、使用js的ajax局部刷新功能,每次刷新将数据库中读取出的新记录插入到页面的显示区域,代码如下: [removed] =setInterval(showWords1000);//加载完成之后开始执行刷新功能 function showWords()//刷新时被...

    我的通讯录

    动态生成要执行的SQL语句.(System.asp) (3).JS写成类,运用AJAX框架prototype.js局部更新页面信息,减少客户端等待.验证客户端数据时运用JS正则表达式 (4).封装操作类. 将用到的操作写成一个类,当运行出错时...

    Visual C#2008开发经验与技巧宝典 源码

    WCF多层数据架构通信、泛型应用、XML文件处理、多线程管理、程序异常拦截、文件压缩及解压缩、文件加密和解密、文件访问权限、API函数调用、指针调用、数据更新并发冲突处理、数据批量导入导出、Web服务、MS Report ...

    DevPage2005 分页控件Demo源码 只要2分

    对于SEO优化来说AJAX分页及局部刷新分页,在百度,Google等搜索引擎收录来说十分不利,因为搜索引擎都是靠URL来记录的。 1、在工具栏选择项然后浏览控件DevPage Vs2005 Release 1.0 控件目录 2、修改WebConfig里的Sql...

    DevPage2005 分页控件Demo源码

    对于SEO优化来说AJAX分页及局部刷新分页,在百度,Google等搜索引擎收录来说十分不利,因为搜索引擎都是靠URL来记录的。 1、在工具栏选择项然后浏览控件DevPage Vs2005 Release 1.0 控件目录 2、修改WebConfig里的Sql...

    ExtAspNet_v2.3.2_dll

    -ExtAspNet支持原生的AJAX,也就是说控件的属性改变在AJAX过程中会反映到页面中,但并不是所有的控件属性都支持AJAX改变。 -加载s.gif图片在本机进行,不会请求extjs.com远程资源(feedback:efrigate43,abaocoole)...

    ASP.NET4高级程序设计第4版 带目录PDF 分卷压缩包 part1

    此外,《ASP.NET 4高级程序设计(第4版)》专门提供了两章的内容来教你如何用Ajax 技术制作快速响应的页面,以及如何使用微软的ASP.NETAJAX平台。另外,还专门介绍了ASP.NET4 新增的功能,如MVC 和动态数据等。  ...

    ExtAspNet v2.2.1 (2009-4-1) 值得一看

    -优化AJAX的内部实现,每个页面保存的ViewState现在减少1/3左右(重要更新)。 -优化Tree节点的NodeId自动生成,减少ViewState占用。 +2009-08-09 v2.0 beta5 +ExtAspNet和Asp.net的提交按钮兼容问题...

    亮剑.NET深入体验与实战精要2

    3.3.1 页面数据绑定全攻略 131 3.3.2 Bind和Eval的区别 140 3.4 ASP.NET编程中的技巧 142 3.4.1 页面之间传值的7种方法 142 3.4.2 get与post方法的区别 146 3.4.3 ASP.NET服务器控件和 HTML控件的区别 146 3.4.4 ...

    亮剑.NET深入体验与实战精要3

    3.3.1 页面数据绑定全攻略 131 3.3.2 Bind和Eval的区别 140 3.4 ASP.NET编程中的技巧 142 3.4.1 页面之间传值的7种方法 142 3.4.2 get与post方法的区别 146 3.4.3 ASP.NET服务器控件和 HTML控件的区别 146 3.4.4 ...

    最新Python3.5零基础+高级+完整项目(28周全)培训视频学习资料

    主机管理项目动态调用插件进行数据解析 主机管理项目对模块中的参数进行解析 第24周 本节题纲 上节内容回顾 ModelForm操作及验证 ajax操作-原生ajax ajax操作-JQuery的ajax ajax操作-伪ajax(iframe) ajax操作-...

    ASP.NET4高级程序设计(第4版) 3/3

    此外,《ASP.NET 4高级程序设计(第4版)》专门提供了两章的内容来教你如何用Ajax 技术制作快速响应的页面,以及如何使用微软的ASP.NETAJAX平台。另外,还专门介绍了ASP.NET4 新增的功能,如MVC 和动态数据等。  ...

    基于J2EE框架的个人博客系统项目毕业设计论文(源码和论文)

    2、 Ajax我们主要应用就是xmlhttprequest,回调函数实现局部刷新达道数据更新! 4.2需求分析 Blog网站主要是实现注册用户登录、管理相关信息、博文及相关评论、查看留言、友情链接、及图片的上传和图像的播放而为...

Global site tag (gtag.js) - Google Analytics