AJAX 自学练习 无刷新提交并修改数据库数据并显示

request.jsp页面中有rocarsId,和ccrn两个text。
对应在数据库中表格 rocars表的msg_id,ccrn两个字段。现在要实现在界面上修改ccrn的值,ajax提交到response.jsp页面,并调用RocarsEntiy.updateCcrn方法更新对应的ccrn,最后无刷新显示
代码:
request.jsp


代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="javascript"><!--
function GetXmlHttpObject(){
    var xmlHttp = null;
    try{
        xmlHttp = new XMLHttpRequest();
    }catch(e){
        try{
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;

}
function updateCcrn(rocarsId,ccrn){
alert(rocarsId)
alert(ccrn)
    xmlHttp = GetXmlHttpObject();
    if(xmlHttp == null){
        alert ("you browser don't support the ajax");
         return;
    }
    var url = "./response.jsp";
    url = url + "?rocarsId="+ rocarsId;
    url = url + "&ccrn="+ ccrn;
    url = url + "&sid ="+ Math.random();
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
function getCcrn(str){
    xmlHttp = GetXmlHttpObject();
    if(xmlHttp == null){
        alert ("you browser don't support the ajax");
         return;

}
    var url = "./response.jsp";
    url = url + "?q="+ str;
    url = url + "&sid ="+ Math.random();
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}
function stateChanged()
{
    if(xmlHttp.readyState==4)
    {
        document.getElementById("rocarsccrn").value = xmlHttp.responseText;
    }
}
// --></script>
</head>
<body>
<form name="form1" action="" method="post">
    <label>rocarsId:</label><input type="text" name="rocarsId" value="140" />
    <label>ccrn:</label><input type="text" id="rocarsccrn" name="rocarsccrn" onchange="updateCcrn(document.form1.rocarsId.value,this.value)"/>
</form>
</body>
</html>

response.jsp


代码如下:

<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.lwf.eus.util.*,java.util.*,com.lwf.eus.entity.*,com.lwf.eus.bean.*" %>
<%
    String rocarsId = request.getParameter("rocarsId");
    String ccrn = request.getParameter("ccrn");
    System.out.println("rocarsId:" + rocarsId);
    System.out.println("ccrn:" + ccrn);
    RocarsEntity.updateCcrnById(rocarsId,ccrn);
    out.print(ccrn);
%>

RocarsEntity.java


代码如下:

package com.lwf.eus.entity;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import com.lwf.eus.bean.RocarsBean;
import com.lwf.eus.util.ConnectionManager;
public class RocarsEntity {
    public static Vector getRocarsList() {
        Vector vRocars = new Vector();
        //Connection conn = ConnectionManager.getConnection();
        Connection conn = ConnectionManager.getConnectionFromDS();
        Statement st = ConnectionManager.createStatement(conn);
        String sql = "select msg_id,ccrn from rocars";
        ResultSet rs = null;
        try {
            rs = st.executeQuery(sql);
            while (rs.next()) {
                RocarsBean rocars = new RocarsBean();
                rocars.setRocarsId(rs.getString(1));
                rocars.setCcrn(rs.getString(2));
                vRocars.addElement(rocars);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return vRocars;
        }

}

public static RocarsBean getRocarsListById(String rocarsId){
        Connection conn = ConnectionManager.getConnectionFromDS();
        Statement st = ConnectionManager.createStatement(conn);
        String sql = "select * from rocars where msg_id=" + rocarsId;
        ResultSet rs = null;
        RocarsBean rocars= null;
        try {
            rs = st.executeQuery(sql);
            rocars = new RocarsBean();
            while (rs.next()) {                
                rocars.setRocarsId(rs.getString("msg_id"));
                rocars.setCcrn(rs.getString("ccrn"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return rocars;
        }
    }
    public static void updateCcrnById(String rocarsId, String ccrn)
    {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = ConnectionManager.getConnectionFromDS();
            stmt = ConnectionManager.createStatement(conn);
            String sqlStr = "update rocars set ccrn= '"+ ccrn + "'" + "where msg_id=" + rocarsId ;
            stmt.executeUpdate(sqlStr);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{

try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

ConnectionManager.java
这里可以直接使用JDBC也可以调用weblogic的数据源JNDI。


代码如下:

package com.lwf.eus.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionManager {
    public static Connection getConnection(){
        Connection conn = null;
        String url = "jdbc:postgresql://192.168.0.180/getseus";
        String userName = "getsdbadmin";
        String pwd = "powerdb";
        try {
            Class.forName("org.postgresql.Driver").newInstance();
            conn = DriverManager.getConnection(url,userName,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }

return conn;
    }

public static Connection getConnectionFromDS(){
        Connection conn = null;
        Context ctx = null;
        try {
            ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("JNDIPG");
            conn = ds.getConnection();
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

return conn;

}

public static Statement createStatement(Connection conn){
        Statement st = null;
            try {
                st = conn.createStatement();

} catch (SQLException e) {
                e.printStackTrace();
            }
        return st;
    }
}

(0)

相关推荐

  • ajax实现修改功能

    这段时间在做项目,发现自己忘得好快呀,幸亏有博客园帮我记着呢,整理博客园简直不要太重要了哦 因为做的是一个内部管理系统,只用了一个主页面,所有的都不允许整个网页刷新,所以我们只能用ajax 来做,当然刚开始做也走了很多的弯路,最终还是做出来了 这点还是比较欣慰的 今天要整理一下ajax实现修改功能 这里的login登录也不写了,主要是写一下修改的大体代码,方便以后 用的时候查找 样式我用的是bootstrap,一开始要引入三个文件,这里就不多说了,下面是页面所要显示的样式 <div class=

  • jquery ajax双击div可直接修改div中的内容

    最近在做后台功能开发的时候,用到对排序字段的修改,感觉只为了修改一个排序值,而要重新进入编辑页比较麻烦,于是网上找点资料自己动手写了一个jquery双击实现直接修改排序值的效果: html代码: <div title="[双击可直接修改]" class="changeSort" id="{$id}">{$sort}</div> JS代码: <script type="text/javascript"

  • 用Jquery实现可编辑表格并用AJAX提交到服务器修改数据

    下面是js Code: 复制代码 代码如下: $(function() { // 相当于在页面中的body标签加上onload事件 $(".caname").click(function() { // 给页面中有caname类的标签加上click函数 var objTD = $(this); var oldText = $.trim(objTD.text()); // 保存老的类别名称 var input = $("<input type='text' value='&

  • jquery ajax修改全局变量示例代码

    今天工作的时候遇到一个问题 代码如下: 复制代码 代码如下: var status=1; var ob=$("[name='email']"); $.ajax({ url:"{:U('Home/Index/checkemail')}", data:"email="+query.email, type:"post", dataType:"json", success:function(re){ status=

  • Ajax修改购物车示例

    1.购物车类的设计 ShoppingCartItem:书的封装,包括书名,数量,价格三个属性,以及对应的getter和setter方法. ShoppingCart:购物车封装类,items为 Map<String, ShoppingCartItem> ,以及加入购物车,得到购物车中书的总数量以及总价格三个函数. 2:jsp加入购物车,超链接中带入书名以及价格 <body> <!-- 加入span的目的是为了定位 --> <div id="cartstat

  • jQuery+ajax实现鼠标单击修改内容的思路

    现有表格中的一行的代码如下所示: 效果可以看下具体51搜索展示http://www.51bt.cc,结合Xunsearch全文检索技术,可以达到毫秒级的数据搜索 <tr> <td><span class="catid">2</span></td> <td>公司介绍</td> <td>内部栏目</td> <td><span class="listorde

  • php通过ajax实现双击table修改内容

    复制代码 代码如下: <script type="text/javascript"> $(function() { $("td").dblclick(function() { //获取标签 var td = $(this); var itemid=td[0].id; var txt = td.text(); var input = $("<input type='text' value='" + txt + "'/&g

  • jQuery+ajax实现鼠标单击修改内容的方法

    现有表格中的一行的代码如下所示: <tr> <td><span class="catid">2</span></td> <td>公司介绍</td> <td>内部栏目</td> <td><span class="listorder" title="点击修改">2</span></td> <

  • Ajax修改数据即时显示篇实现代码

    我们这次要请求的服务端网页是:Edit_Data.Asp 待会我会在本次ajax教程中提供该asp文件的源码. 其实在你学会了怎么使用ajax添加数据时,想实现修改数据对你来说已经很容易了!费话不说先看前端的JavaScript代码和本次的ajax实例效果! 复制代码 代码如下: <html> <head> <title>ajax修改数据</title> <style> body{ font-size:12px; } </style>

  • jquery formValidator插件ajax验证 内容不做任何修改再离开提示错误的bug解决方法

    query formValidator插件非常好用,但是有一个严重的Bug,在使用ajax验证的时候,如果输入框的内容已经存在,把鼠标放到输入框,不做任何修改再离开,则会提示错误, 这是这个插件犯的一个很愚蠢的错误 复制代码 代码如下: oneIsValid: function(id, index) { var returnObj = new Object(); returnObj.id = id; returnObj.ajax = -1; returnObj.errormsg = ""

随机推荐