概述
最近用jquery写了一个插件,感觉挺有用的,于是记录下来分享给在IT路上奔跑的程序猿,好跟不好另外说,如果觉得好的话就拿去。好了不bb了。
这个插件是链接数据库采用了DAO的设计模式,前台只用两三行的代码就可以将一个表格的基本功能给实现(增删改查,ajax分页,模糊搜索,还有就是每页 显示的记录数),参数的话只要给一个serlvet地址就可以了,数据的发送则采用了json格式。后台的servlet要自己编写,代码也不是很多。
前台代码:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/test01.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Tab").baseFn({url: "AdminServelt08"});
});
</script>
</head>
<body>
<div id="Tab"></div>
</body>
</html>
后台代码:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import vo.Admin;
import factory.ServiceFactory;
@WebServlet("/AdminServelt08")
public class AdminServelt08 extends HttpServlet {
private static final long serialVersionUID = 1L;
public AdminServelt08() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
List<Admin> all = new ArrayList<Admin>();
String req = request.getParameter("send");
if ("read".equals(req)) {
try {
String start = request.getParameter("start");
String size = request.getParameter("size");
String keyWord = request.getParameter("kw");
//System.out.println(start + "-" + size);
if (keyWord != null) {
all = ServiceFactory.getAdminServiceInstance().findAll(keyWord);
}
else if (start != null && size != null) {
all = ServiceFactory.getAdminServiceInstance().pagination(Integer.parseInt(start), Integer.parseInt(size));
} else {
all = ServiceFactory.getAdminServiceInstance().pagination(0, 5);
}
Integer allCount = ServiceFactory.getAdminServiceInstance().findAll("").size();
Admin admin = null;
String str = "{"allCount":"" + allCount + "",";
str += ""admin":[";
for (int i=0; i<all.size(); i++) {
str = str + "{";
admin = new Admin();
admin = all.get(i);
str = str + ""adId":"" + admin.getAdid() + "",";
str = str + ""adName":"" + admin.getAdname() + "",";
str = str + ""adPass":"" + admin.getAdpass() + "",";
str = str + ""adPhone":"" + admin.getAdphone() + "",";
str = str + ""adEmail":"" + admin.getAdemail() + "",";
str = str + ""adQQ":"" + admin.getAdqq() + """;
str = str + "},";
}
str = str.substring(0, str.length()-1);
str = str + "]}";
out.print(str);
out.close();
//
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
else if ("insert".equals(req)) {
String data = request.getParameter("addData");
try {
JSONArray ja = new JSONArray(data);
JSONObject jo = null;
Admin admin = new Admin();
for (int i=0; i<ja.length(); i++) {
jo = new JSONObject();
admin.setAdid(ja.getJSONObject(0).getInt("adId"));
admin.setAdname(ja.getJSONObject(1).getString("adName"));
admin.setAdpass(ja.getJSONObject(2).getString("adPass"));
admin.setAdphone(ja.getJSONObject(3).getString("adPhone"));
admin.setAdemail(ja.getJSONObject(4).getString("adEmail"));
admin.setAdqq(ja.getJSONObject(5).getString("adQQ"));
}
if (ServiceFactory.getAdminServiceInstance().doCreate(admin)) {
out.print("[{"success":"true"}]");
} else {
out.print("[{"success":"false"}]");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else if ("update".equals(req)) {
String data = request.getParameter("updateData");
try {
JSONArray ja = new JSONArray(data);
JSONObject jo = null;
Admin admin = new Admin();
for (int i=0; i<ja.length(); i++) {
jo = new JSONObject();
admin.setAdid(ja.getJSONObject(0).getInt("adId"));
admin.setAdname(ja.getJSONObject(1).getString("adName"));
admin.setAdpass(ja.getJSONObject(2).getString("adPass"));
admin.setAdphone(ja.getJSONObject(3).getString("adPhone"));
admin.setAdemail(ja.getJSONObject(4).getString("adEmail"));
admin.setAdqq(ja.getJSONObject(5).getString("adQQ"));
}
if (ServiceFactory.getAdminServiceInstance().doUpdate(admin)) {
out.print("[{"success":"true"}]");
} else {
out.print("[{"success":"false"}]");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else if ("delete".equals(req)){
String data = request.getParameter("delData");
String [] ids = data.split(",");
boolean flag = false;
for (int i=0; i<ids.length; i++) {
try {
if (ServiceFactory.getAdminServiceInstance().doDelete(Integer.parseInt(ids[i]))) {
flag = true;
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
if (flag) {
out.print("[{"success":"true"}]");
}
else {
out.print("[{"success":"false"}]");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
js插件:
(function($){
var this_id = "";
var serlvletUrl = "";
$.fn.baseFn = function(options) {
//获取id的名字
this.each(function () { this_id = $(this).attr("id"); });
//设置默认值
var defaults = {
url: "",
};
// Extend our default options with those provided.
var opts = $.extend(defaults, options);
servletUrl = opts.url;
initpage();
};
//初始化页面
function initpage() {
$.ajax({ type:"post", url:servletUrl, data:{send:"read"}, dataType:"json", success:function(rdata) { var currentPage = 1; var pageSize = 5; initTab(rdata, currentPage, pageSize); } });
}
//***表格初始化******************************************************
function initTab(rdata, currentPage, pageSize) {
var tab = "<table border=1 width=800 cellpadding=0 id=adminTab>";
var count = 0;
$(rdata.admin).each(function(index, item) { //这里的each是每一个amind对象 if (index == 0) { //构建表头 tab = tab + "<tr align=center id=h>"; tab = tab + "<td><input type=checkbox id=checkall />checkall</td>"; for (var i in item) { tab = tab + "<td>" + i + "</td>"; count++; } tab = tab + "</tr>"; } tab = tab + "<tr align=center>"; tab = tab + "<td><input type=checkbox /> </td>"; for (var i in item) { tab = tab + "<td>" + item[i] + "</td>"; } tab = tab + "</tr>"; });
tab = tab + "<tr align=center><td colspan=" + (count+1) +">";
tab += "currentPage<input type=text id=pn size=5 />";
tab += "<input type=button value=GO id=jump />";
tab += "<input type=button value=prePage class=prePage
/>";
tab += "<input type=button value=nextPage class=nextPage
/>";
tab += "show <input type=text id=pageSize size=5 />records ";
tab += "there are " + rdata.allCount +" records/" + Math.ceil(rdata.allCount / pageSize) +"pages";
tab += "</td></tr>";
tab = tab + "</table>";
$("#" + this_id).html(tab);
//添加功能按钮
var ta="";
ta += "<tr align=center><td colspan=" + (count+1) + ">";
ta += "<input type=button value=add class=create />";
ta += "<input type=button value=update class=update />";
ta += "<input type=button value=delete class=delete />";
ta += "search by adName <input type=text id=search /><input type=button class=search value=search />";
ta += "</td></tr>";
$("#h").before(ta);//before:在什么之前添加
//全选按钮
$("#checkall").click(function() { if ( $(this).attr("checked") ) { $("input:checkbox").attr("checked", true); } else { $("input:checkbox").attr("checked", false); } });
//点击add按钮
$(".create").click(function () { createTable(rdata); });
//点击uddate按钮
$(".update").click(function () { updateTab(rdata); });
//点击delete按钮
$(".delete").click(function () { deleteTab(); });
//点击搜索
$(".search").click(function () { var keyword = $("#search").val(); search(keyword); });
//点击跳转
$("#jump").click(function () { var pageNum = $("#pn").val(); if (pageNum > 0 && pageNum <= Math.ceil(rdata.allCount / 5)) { gotopage(pageNum, pageSize); } else { alert("input error!"); } });
//上一页
$(".prePage").click(function () { currentPage--; var pageNum = currentPage; if (pageNum == 0) { $(".prePage").attr({"disabled":"disabled"}); return; } else { gotopage(pageNum, pageSize); } });
//下 一页
$(".nextPage").click(function () { currentPage++; var total = rdata.allCount; var pageNum = currentPage; if (pageNum == (Math.ceil(total / 5)+1)) { $(".nextPage").attr({"disabled":"disabled"}); return; } else { gotopage(pageNum, pageSize); } });
//每页显示的记录
$("#pageSize").blur(function () { currentPage = 1; pageSize = $("#pageSize").val(); gotopage(currentPage, pageSize); });
$("#pn").val(currentPage);
$("#pageSize").val(pageSize);
}
//添加操作 ********************************************************
function createTable(rdata) {
$("#adminTab").after("<div id=zhezao></div>");
shade();
var createtab = "<table width=300 border=1 cellpadding=0 id=addtotab>";
var createtab = createtab + "<tr><td colspan=2 align=center>Add Please</td></tr>";
$(rdata.admin).each(function(index,item) { for (var i in item) { if (index == 0) { createtab = createtab + "<tr><td>" + i + "</td>"; createtab = createtab + "<td><input type=text id=" + i + " /></td></tr>"; } } });
createtab = createtab + "<tr><td colspan=2 align=center><input type=button value=submit class=ok /><input type=button value=reset class=cancle /></td></tr>";
createtab = createtab + "</table>";
$("#zhezao").after(createtab);
$("#addtotab").css({"display":"", "position":"fixed", "background":"#fff", "z-index":1001, "left":$(window).width()/2-150, "top":$(window).height()/2-150 });
//点击reset按钮
$(".cancle").click(function() { $("#addtotab").remove(); $("#zhezao").remove(); });
//点击submit按钮之后对数据进行json封装
$(".ok").click(function() { var str = "["; $(rdata.admin).each(function(index,item) { if (index == 0) { for (var i in item) { str = str + "{"" + i + "":"" + $("#"+i).val() + ""},"; } str = str.substring(0,str.length-1); str = str + "]"; } }); //发送添加数据 $.ajax({ type:"post", url:servletUrl, data:{send:"insert",addData:str}, dataType:"json", success:function(getdata) { if (getdata[0]["success"] == "true") { alert("add successful!"); initpage(); } else { alert("add false"); } $("#addtotab").remove(); $("#zhezao").remove(); } }); });
}
//update操作 ************************************************************
function updateTab(rdata) {
var len = $("input:not('#checkall'):checked").length;
if (len == 0) {
alert("please select one to update");
}
else if (len > 1){
alert("update only one!")
}
else {
$("#adminTab").after("<div id=zhezao></div>");
shade();
var createtab = "<table width=300 border=1 cellpadding=0 id=addtotab>";
var createtab = createtab + "<tr><td colspan=2 align=center>Update Please</td></tr>";
$(rdata.admin).each(function(index,item) { var isId = true; for (var i in item) { if (index == 0) { if (isId) { isId = false; createtab = createtab + "<tr><td>" + i + "</td>"; createtab = createtab + "<td><input type=text disabled=disabled id=" + i + " /></td></tr>"; continue; } createtab = createtab + "<tr><td>" + i + "</td>"; createtab = createtab + "<td><input type=text id=" + i + " /></td></tr>"; } } });
createtab = createtab + "<tr><td colspan=2 align=center><input type=button value=submit class=ok /><input type=button value=reset class=cancle /></td></tr>";
createtab = createtab + "</table>";
$("#zhezao").after(createtab);
$("#addtotab").css({"display":"", "position":"fixed", "background":"#fff", "z-index":1001, "left":$(window).width()/2-150, "top":$(window).height()/2-150 });
//点击reset按钮
$(".cancle").click(function() { $("#addtotab").remove(); $("#zhezao").remove(); });
$(rdata.admin).each(function(index,item) { if (index == 0) { var cnt = 1; for (var i in item) { var updateVal = $("input:not('#checkall'):checked").parent().parent().children("td:eq(" + cnt + ")").text(); $("#"+i).attr("value",updateVal); cnt++; } } });
$(".ok").click(function() { var updatestr = "["; $(rdata.admin).each(function(index, item) { if (index == 0) { for (var i in item) { updatestr = updatestr + "{"" + i + "":"" + $("#"+i).val() + ""},"; } updatestr = updatestr.substring(0,updatestr.length-1); updatestr = updatestr + "]"; } }); //发送更新数据 $.ajax({ type:"post", url:servletUrl, data:{send:"update", updateData:updatestr}, dataType:"json", success:function(getda) { if (getda[0]["success"] == "true") { alert("update successful"); initpage(); } else { alert("update fail"); } $("#addtotab").remove(); $("#zhezao").remove(); } }); });
}
}
//delete操作**********************************************************************
function deleteTab() {
var len = $("input:not('#checkall'):checked").length;
if (len == 0) {
alert("please select one or more");
}
else {
if (confirm("Do you want to delete?")) { var delstr = ""; $("input:not('checkall'):checked").each(function(index, item) { delstr = delstr + $(this).parent().parent().children("td:eq(1)").text() + ","; }); delstr = delstr.substring(0,delstr.length-1); $.ajax({ type:"post", url:servletUrl, data:{send:"delete", delData:delstr}, dataType:"json", success:function(getdata) { if (getdata[0]["success"] == "true") { alert("delete successful"); initpage(); } else { alert("delete fail"); } } }); }
}
}
//search**************************************************
function search(keyword) {
$.ajax({ url : servletUrl, data:{send:"read", kw:keyword}, cache : false, type : "POST", dataType : "json", success : function (result){ // alert(typeof(result)); initTab(result,0,5); } });
}
//遮罩开始
function shade() {
var winw = $(window).width();
var winh = $(window).height();
$("#zhezao").css({"display":"", "position":"fixed", "background":"#000", "z-index":1000, "-moz-opacity":"0.5", "opacity":".50", "filter":"alpha(opacity=50)", "left":0, "top":0, "width":winw, "height":winh });
}//遮罩结束
//发送分页的数据 *************************************************
function gotopage(pageNum,pageSize) {
var startPoint = (pageNum-1) * pageSize;
$.ajax({ type:"post", url:servletUrl, data:{send:"read",start:startPoint,size:pageSize}, dataType:"json", success:function(data) { initTab(data, pageNum, pageSize); } });
}
})(jQuery);
效果图:
添加操作:
模糊查询:
显示记录数:
好了,文章写到这里,这是我第一篇文章,写得有点粗糙,代码呢也写得有点粗糙,还请见谅!
最后
以上就是超级太阳为你收集整理的ajax+json+servlet实现表格的基本功能的全部内容,希望文章能够帮你解决ajax+json+servlet实现表格的基本功能所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复