jquery的ajax使用--ajax和struts操作数据库
一、实验目的
1.掌握jQuery的事件绑定;
2.掌握jQuery的事件处理函数;
3.掌握jQuery的遍历方法;
4. 掌握jQuery的动态添加元素;
5. 使用jQuery选择器及jQuery对象。
二、实验内容
1.对订单记录进行删除操作;
2.对订单记录进行修改操作;
3.动态添加订单记录;
4.实现订单的全选功能;
5.实现订单的批量删除功能;
三、实验步骤
1.了解Struts2的执行流程
(1)客户端发送一个request。
(2)程序调用StrutsPrepareAndExecuteFilter,询问ActionMapper是否调用某个
Action。
(3)StrutsPrepareAndExecuteFilter会把请求的处理交给ActionProxy。
(4)ActionProxy通过Configuation Manager从struts.xml读取框架的配置信息,找到需
要调用的Action。
(5)ActionProxy创建一个ActionInvocation的实例。
(6)ActionInvocation在调用Action前会依次调用所有配置的拦截器。
(7)Action执行完返回结果字符串,ActionInvocation查找字符串对应的result。
(8)result返回给ActionInvocation过程中,拦截器再次执行(与之前相反)。
(9)产生一个response行为,通过StrutsPrepareAndExecuteFilter反馈给客户端。
图1 struts2的执行流程图
- 简单的说:
客户端发送一个请求(url:xxxAction);
首先到web.xml的FilterDispatcher;
在struts.xml找到xxxAction并调用它的方法(默认是execute());
该方法在后端执行一些列操作之后通过它的返回值(默认有SUCCESS,ERROR,NONE,LOGIN,INPUT)找到相应的result
最后通过StrutsPrepareAndExecuteFilter给javascript,由ajax或其他方式获取。
Js通过事件动态的显示到JSP或者HTML界面。
四、实验效果
1.查询
增加商品信息
在待定操作中输入商品的属性,单击增加按钮。
再次查询
2.删除操作
-在操作的那个字段下点击你要删除的那一栏就可以啦。
-点击商品编号为4的那一栏的删除,刷新数据库查看goods表的结果。
、
3.更新操作
-对要修改的信息进行输入编辑,点击那一栏的修改。
-修改苹果的价格5->10,数量2->10,点击修改
、
4.批量删除
-选择全选字段下的复选框,点击批量删除。
-若没有选择选项,直接点击批量删除。
-增加5,5,5,5,5;2,2,2,2作为批量删除的商品测试。
-单击批量删除
5.按照价格范围查询
-先添加几组不同价格的商品。
-当前的所有商品如图所示
-查询50-200的商品,点击价格查询
6.全选操作
-单击全选按钮,选中所有复选框,并将全选按钮的值改成全不选。
五、代码实现
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv ="proma" content = "no-cache"/>
<meta http-equiv="cache-control" content="no cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<script type="text/javascript" src="js/ajaxHandle.js"></script>
<style>
#total{
text-align:center;
line-height:40px;
margin:0 auto;
}
table{
text-align:center;
margin:auto;
}
</style>
</head>
<body>
<div id="total">
<button id="btnSubmit">增加</button>
<button id="btnFindAll">查询</button>
<button id="btnMultiDelete">批量删除</button>
<button id="btnFindByPrice">价格查询</button>
<button id="btnFindByCount">数量降序查询</button>
<input type="text" id="lowPrice" style="height:15px;width:30px"> ——
<input type="text" id="highPrice" style="height:15px;width:30px">
<br>
<table id="table1">
<tr>
<th>
<input type="button" id="allck" onclick="allCheck('ckbox')" value="全选">
</th>
<th>商品编号</th>
<th>商品名称</th>
<th>商品数量</th>
<th>价格</th>
<th>地点</th>
<th>操作</th>
</tr>
<tr>
<td>待定操作</td>
<td><input type="text" class="txt1"></td>
<td><input type="text" class="txt1"></td>
<td><input type="text" class="txt1"></td>
<td><input type="text" class="txt1"></td>
<td><input type="text" class="txt1"></td>
</tr>
</table>
</div>
</body>
</html>
- ajaxHandle.js
//1.tr.attr("id");获取tr的id
//2.$(this).css("",""); $(this).addClass("");
//tr颜色交替
function alter()
{
$("tr:odd").css("background-color", "#ADD8E6");
$("tr:even:gt(0)").css("background-color", "#b0c4de");
}
//划过tr的颜色变化
function changeColor()
{
$("#table1 tr").hover(
function()
{
$(this).css("background-color","pink");//$(this).addClass("trOver");
},
function()
{
$("tr:odd").css("background-color", "#ADD8E6");
$("tr:even").css("background-color", "#b0c4de");
$("tr").eq(0).css("background-color","white");
}
)
}
//JSP的删除
function removeJsp(event){
var tr=$(event).parents("tr").remove();
}
//删除
function remove(event)
{
var tr=$(event).parents("tr");
//数据库的删除
var num=tr.find("td").eq(1).find("input").val();
$.ajax({
type:"post",
url:"del",
data:{
num:num
},
datatype:"json",
success:function(){
tr.remove();},
error:function(){}
});
}
//修改
function update(event){
var tr=$(event).parents("tr");
var num=tr.find("td").eq(1).find("input").val();
var name=tr.find("td").eq(2).find("input").val();
var count=tr.find("td").eq(3).find("input").val();
var price=tr.find("td").eq(4).find("input").val();
var place=tr.find("td").eq(5).find("input").val();;
$.ajax({
type:"post",
url:"update",
data:{
num:num,
name:name,
count:count,
price:price,
place:place
},
datatype:"json",
success:function(){
},
error:function(){
}
});
}
var flag=true;
//全选
function allCheck(obj){
var btn=$("#allck");
var ckboxs=document.getElementsByName(obj);
if(flag==true){
for(var i=0;i<ckboxs.length;i++){
ckboxs[i].checked="checked";
}
flag=false;
btn.val("全不选");
}
else if(flag==false){
for(var i=0;i<ckboxs.length;i++){
ckboxs[i].checked="";
}
flag=true;
btn.val("全选");
}
}
//取消全选
function noAllCheck(obj){
var ckboxs=document.getElementsByName(obj);
if(null!=ckboxs){
for(var i=0;i<ckboxs.length;i++){
ckboxs[i].checked="";
}
}
}
//主函数
$(document).ready(function(){
var $btn=$("#btnSubmit");
var $btnDel=$("#btnDelete");
var $btnUpdate=$("#btnUpdate");
var $btnFindByPrice=$("#btnFindByPrice");
var $btnFindByCount=$("#btnFindByCount");
var $btnMultiDel=$("#btnMultiDelete");
var $btnFindAll=$("#btnFindAll");
//数据库和Jsp增加数据
$btn.bind("click",function(){
var tr=$("#table1").find("tr:eq(1)");
var num=tr.find("td").eq(1).find("input").val();
var name=tr.find("td").eq(2).find("input").val();
var count=tr.find("td").eq(3).find("input").val();
var price=tr.find("td").eq(4).find("input").val();
var place=tr.find("td").eq(5).find("input").val();
$.ajax({
type:"post",
url:"add",
data:{
num:num,
name:name,
price:price,
count:count,
place:place
},
datatype:"json",
success:function(){
//addJsp();
alert("add success!");
},
error:function(){
alert("add error--ajax");
}
});
});
//批量删除
$btnMultiDel.bind("click",function(){
var msg=confirm("确定删除所选吗?");
if(msg==true){
var checks = $("input[name='ckbox']:checked");
if(checks.length == 0){
alert("没有选中任何选项");
return false;
}
$("input[name='ckbox']:checked").each(function(){
remove(this);
});
}
});
//getJSON
$btnFindAll.bind("click",function(){
var message="1234";
$.ajax({
type:"post",
url:"findAll",
data:{result:message},
datatype:"json",
success:function(result){
//alert("result---"+result);
$("input[name='ckbox']:not(:checked)").each(function(){
removeJsp(this);
});
var data=eval("("+result+")");
var len = $("#table1 tr").length;
$.each(data,function(i,element){
//alert(this.name+"--"+this.num+"--"+this.price+"--"+this.place+"--"+this.count);
$("#table1").append("<tr id=t"+len+" align='center'>"
+"<td><input type='checkbox' name='ckbox'></td>"
+"<td><input type='text' class='txt1' value="+this.num+"></td>"
+"<td><input type='text' class='txt1' value="+this.name+"></td>"
+"<td><input type='text' class='txt1' value="+this.count+"></td>"
+"<td><input type='text' class='txt1' value="+this.price+"></td>"
+"<td><input type='text' class='txt1' value="+this.place+"></td>"
+"<td><a href='#' onclick='remove(this)'>删除</a>" +
" <a href='#' onclick='update(this)'>修改</a></td>"
+"</tr>");
changeColor();
alter();
});
},
error:function(){
alert("获取json出现异常--查询全部");
}
});
});
//按价格范围查询
$btnFindByPrice.bind("click",function(){
var message="123";
var lowPrice=$("#lowPrice").val();
var highPrice=$("#highPrice").val();
$.ajax({
type:"post",
url:"findByPrice",
data:{
result:message,
lowPrice:lowPrice,
highPrice:highPrice
},
datatype:"json",
success:function(result){
//alert("result---"+result);
$("input[name='ckbox']:not(:checked)").each(function(){
removeJsp(this);
});
var data=eval("("+result+")");
var len = $("#table1 tr").length;
$.each(data,function(i,element){
//alert(this.name+"--"+this.num+"--"+this.price+"--"+this.place+"--"+this.count);
$("#table1").append("<tr id=t"+len+" align='center'>"
+"<td><input type='checkbox' name='ckbox'></td>"
+"<td><input type='text' class='txt1' value="+this.num+"></td>"
+"<td><input type='text' class='txt1' value="+this.name+"></td>"
+"<td><input type='text' class='txt1' value="+this.count+"></td>"
+"<td><input type='text' class='txt1' value="+this.price+"></td>"
+"<td><input type='text' class='txt1' value="+this.place+"></td>"
+"<td><a href='#' onclick='remove(this)'>删除</a>" +
" <a href='#' onclick='update(this)'>修改</a></td>"
+"</tr>");
changeColor();
alter();
});
},
error:function(){
alert("获取json出现异常--查询全部");
}
});
});
//按照数量降序排序
$btnFindByCount.bind("click",function(){
var message="1234";
$.ajax({
type:"post",
url:"findByCount",
data:{result:message},
datatype:"json",
success:function(result){
//alert("result---"+result);
$("input[name='ckbox']:not(:checked)").each(function(){
removeJsp(this);
});
var data=eval("("+result+")");
var len = $("#table1 tr").length;
$.each(data,function(i,element){
//alert(this.name+"--"+this.num+"--"+this.price+"--"+this.place+"--"+this.count);
$("#table1").append("<tr id=t"+len+" align='center'>"
+"<td><input type='checkbox' name='ckbox'></td>"
+"<td><input type='text' class='txt1' value="+this.num+"></td>"
+"<td><input type='text' class='txt1' value="+this.name+"></td>"
+"<td><input type='text' class='txt1' value="+this.count+"></td>"
+"<td><input type='text' class='txt1' value="+this.price+"></td>"
+"<td><input type='text' class='txt1' value="+this.place+"></td>"
+"<td><a href='#' onclick='remove(this)'>删除</a>" +
" <a href='#' onclick='update(this)'>修改</a></td>"
+"</tr>");
changeColor();
alter();
});
},
error:function(){
alert("获取json出现异常--数量降序");
}
});
});
});
- struts,xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="hello" namespace="/" extends="struts-default,json-default">
<action name="add" class="com.action.addAction">
<result name="success">/index.jsp</result>
</action>
<action name="del" class="com.action.delAction">
<result name="success">/index.jsp</result>
</action>
<action name="update" class="com.action.updateAction">
<result name="success">/index.jsp</result>
</action>
<action name="findAll" method="executeAjax" class="com.action.findAllAction">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
<action name="findByPrice" class="com.action.findByPriceAction">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
<action name="findByCount" class="com.action.findByCountAction">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
</package>
</struts>
- Goods.java
package com.vo;
public class Goods {
private int num;
private String name;
private int price;
private int count;
private String place;
public Goods() {}
//增加goods
public Goods(String name,int price,int count,String place) {
this.name=name;
this.price=price;
this.count=count;
this.place=place;
}
//查询goods
public Goods(int num,String name,int price,int count,String place) {
this.num=num;
this.name=name;
this.price=price;
this.count=count;
this.place=place;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "\ngoods[ num="+num+" name="+name+" price="+price+" place="+place+" count="+count;
}
}
- GoodsDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.vo.Goods;
public class GoodsDao {
private PreparedStatement ps;
private static DBHandler d=new DBHandler();
private static Connection conn=d.getConnection();
public GoodsDao(){}
//增加商品
public void addGoods(Goods goods) throws SQLException {
String sql="insert into goods values(?,?,?,?,?)";
if(conn!=null&&!conn.isClosed()) {
ps=conn.prepareStatement(sql);
ps.setInt(1, goods.getNum());
ps.setString(2, goods.getName());
ps.setInt(3, goods.getPrice());
ps.setInt(4, goods.getCount());
ps.setString(5, goods.getPlace());
ps.execute();
System.out.println("增加成功");
ps.close();
}
}
//获取所有商品
public List<Goods> getAllGoods() throws SQLException{
List<Goods> goods=new ArrayList<Goods>();
String sql="select num,name,price,count,place from goods";
if(conn!=null&&!conn.isClosed()) {
ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
Goods good=new Goods(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getInt(4),rs.getString(5));
goods.add(good);
}
rs.close();
ps.close();
System.out.println("查询成功");
}
return goods;
}
//价格范围查询
public List<Goods> getGoodsByPrice(int lowPrice,int highPrice) throws SQLException{
List<Goods> goods=new ArrayList<Goods>();
String sql="select * from goods where price between ? and ?";
if(conn!=null&&!conn.isClosed()) {
ps=conn.prepareStatement(sql);
ps.setInt(1, lowPrice);
ps.setInt(2, highPrice);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
Goods good=new Goods(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getInt(4),rs.getString(5));
goods.add(good);
}
rs.close();
ps.close();
}
return goods;
}
//更新
public boolean update(Goods goods) throws SQLException {
String sql="update goods set num=?,name=?,price=?,count=?,place=? where num=?";
ps=conn.prepareStatement(sql);
ps.setInt(1, goods.getNum());
ps.setString(2, goods.getName());
ps.setInt(3, goods.getPrice());
ps.setInt(4, goods.getCount());
ps.setString(5, goods.getPlace());
ps.setInt(6, goods.getNum());
if(ps.executeUpdate()>0){
ps.close();
System.out.println("更新成功");
return true;
}
System.out.println("更新失败");
return false;
}
//删除
public void delete(int num) throws SQLException {
String sql="delete from goods where num=?";
ps=conn.prepareStatement(sql);
ps.setInt(1, num);
ps.execute();
ps.close();
System.out.println("删除成功");
}
//按照数量长度降序查询
public List<Goods> sort(List<Goods> list) {
Goods[] arr=list.toArray(new Goods[list.size()]);
int m=0,n=0;
for(int i=0;i<arr.length-1;i++)
{
for(int j=0;j<arr.length-i-1;j++)
{
m=arr[j].getCount();
n=arr[j+1].getCount();
if(m<n)
{
Goods t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
List<Goods> list1=Arrays.asList(arr);
return list1;
}
public void print(List<Goods> list){
for(Goods g:list)
System.out.println(g);
}
public void closeConn() {
try {
System.out.println("关闭数据库连接");
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
GoodsDao gd=new GoodsDao();
Goods g=new Goods(3,"xx",11,21,"扬州");
try {
// gd.addGoods(g); //增加
// List<Goods> goods=(ArrayList<Goods>) gd.getAllGoods(); //查询
// System.out.println(goods);
// gd.update(g); //更新
// gd.delete(i); //删除
// List<Goods> goods=(ArrayList<Goods>) gd.getAllGoods(); //查询
// List<Goods> list=gd.sort(goods);//价格排序
// gd.print(list);
int lowPrice=2;
int highPrice=150;
List<Goods> goods=gd.getGoodsByPrice(lowPrice, highPrice);
List<Goods> list=gd.sort(goods);
gd.print(list);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<Goods> getGoodsByPrice(List<Goods> goods) {
// TODO Auto-generated method stub
return null;
}
}
- DBHandler.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHandler {
private static final String driver="com.mysql.jdbc.Driver";
private static final String uri="jdbc:mysql://localhost:3306/Test5880";
private static final String user="root";
private static final String password="root";
private Connection conn=null;
public DBHandler()
{
try {
Class.forName(driver);
this.conn=DriverManager.getConnection(uri, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection()
{
return this.conn;
}
public void close()
{
if(this.conn!=null)
{
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- action类实现增删改查以及过滤查询
//addAction.java
package com.action;
import com.dao.GoodsDao;
import com.opensymphony.xwork2.ActionSupport;
import com.vo.Goods;
public class addAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private GoodsDao goodsDao=new GoodsDao();
private Goods goods=null;
private String num;
private String name;
private String price;
private String count;
private String place;
@Override
public String execute() throws Exception {
System.out.println("num:"+num+"name:"+name+" price:"+price+" count:"+count+" place:"+place);
goods=new Goods(Integer.parseInt(num),name,Integer.parseInt(price),Integer.parseInt(count),place);//增加的商品对象
goodsDao.addGoods(goods);//执行增加操作
System.out.println("action增加成功");
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
//删除
public String execute() throws Exception {
GoodsDao gd=new GoodsDao();
System.out.println("num="+num);
gd.delete(Integer.parseInt(num));//删除数据
System.out.println("action删除成功");
return SUCCESS;
}
//更新
public String execute() throws Exception {
// TODO Auto-generated method stub
GoodsDao gd=new GoodsDao();
goods=new Goods(Integer.parseInt(num),name,Integer.parseInt(price),Integer.parseInt(count),place);
gd.update(goods);
System.out.println("action更新成功");
return SUCCESS;
}
//查询
private String result;
@SuppressWarnings("unused")
public String executeAjax() throws SQLException {
ArrayList<Goods> list=new ArrayList<Goods>();
GoodsDao gd=new GoodsDao();
list=(ArrayList<Goods>) gd.getAllGoods();
//JSONObject json = JSONObject.fromObject(list);
JSONArray json=JSONArray.fromObject(list);
result=json.toString();
return SUCCESS;
}
//价格范围查询
private String result;
private String lowPrice;
private String highPrice;
@Override
public String execute() throws Exception {
GoodsDao gd=new GoodsDao();
ArrayList<Goods> goods=new ArrayList<Goods>();
goods=(ArrayList<Goods>) gd.getGoodsByPrice(Integer.parseInt(lowPrice), Integer.parseInt(highPrice));
List<Goods> list=gd.sort(goods);
JSONArray json=JSONArray.fromObject(list);
setResult(json.toString());
return SUCCESS;
}