DIV CSS 佈局教程網

用Bootstrap打造郵件中心:後端分頁與模態框寫信功能完整實作
編輯:關於JavaScript     

做一個堪用的網頁版郵件中心,通常要同時解決三件事:清單怎麼分頁、刪除怎麼確認、寫信怎麼在一個彈窗裡完成。本文以 Servlet + DAO + JSP + Bootstrap 的組合示範完整流程,前端使用 bootstrap-paginator 產生頁碼、SweetAlert 處理二次確認、KindEditor 承載郵件正文編輯。

一、Servlet 層:用 action 參數分流

所有請求都導向同一支 MailBoxServlet,靠 query string 上的 action 決定要做什麼:page 取分頁資料、delete 刪單筆、pldelete 批次刪除、tree 取收件人樹、save 寫信入庫。回應一律以 JSON 拋回前端,讓同一支 endpoint 服務多種互動。

 package com.rc.controller;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.List;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import net.sf.json.JSONObject;
 import com.rc.dao.R_mailboxDAO;
 import com.rc.daoimpl.R_mailboxDAOimpl;
 import com.rc.dbutil.Sqltools;
 import com.rc.entity.Mailbox;
 import com.rc.entity.R_user;
 import com.rc.entity.TreeNodes;
 import com.rc.util.Page;
 import com.rc.util.PageUtil;
 public class MailBoxServlet extends HttpServlet {
 /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
 @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setContentType("text/html;charset=utf-8");
 String action =request.getParameter("action");
 HttpSession hs = request.getSession(false);
 //讀取登錄人員session
 R_user cuser =(R_user)hs.getAttribute("user");
 PrintWriter out = null;
 R_mailboxDAO mb = new R_mailboxDAOimpl();
 boolean b = true;
 if("page".equals(action)){//查詢所有
 int pageNumber = 0;
 String PageNumberstr = request.getParameter("pageNumber");//從頁面獲取的當前頁
 int count =mb.getcount();
 if(PageNumberstr == null||"".equals(PageNumberstr)){
 pageNumber= 1;
 }else{
 pageNumber = Integer.parseInt(PageNumberstr);//否則強轉
 }
 List <Page> pages = new ArrayList<Page>();
 Page page = PageUtil.createPage(5, count, pageNumber);
 pages.add(page);
 List<Mailbox> mailboxlist = mb.getcostList(page);
 JSONObject obj = new JSONObject();//定義一個json對象
 obj.put("mailbox", mailboxlist);
 obj.put("Page", pages);
 out = response.getWriter();
 out.write(obj.toString());
 }else if("delete".equals(action)){//刪除操作
 String mid = request.getParameter("id");
 JSONObject obj = new JSONObject();
 b =mb.delete(Integer.parseInt(mid));//用boolean接收
 obj.put("biaozhi",b);
 out = response.getWriter();
 out.write(obj.toString());
 }else if("edit".equals(action)){//彈出編輯頁面
 }else if("tedit".equals(action)){//提交編輯信息
 }else if("pldelete".equals(action)){//批量刪除
 JSONObject obj = new JSONObject();
 String deleteidlist = request.getParameter("deleteidlist");
 String[] item = deleteidlist.split(",");
 for (int i = 0; i < item.length; i++) {
 b =mb.delete(Integer.parseInt(item[i]));
 }
 obj.put("biaozhi",b);
 out = response.getWriter();
 out.write(obj.toString());
 }else if("tree".equals(action)){
 List<TreeNodes> treelist = mb.getnodes();
 JSONObject obj = new JSONObject();//定義一個json對象
 obj.put("treelist", treelist);
 out = response.getWriter();
 out.write(obj.toString());
 }else if("save".equals(action)){
 String id = request.getParameter("id");
 String zhuti = request.getParameter("content");
 String content = request.getParameter("content");
 Mailbox mail = new Mailbox();
 mail.setS_id(Integer.parseInt(id));//收件人
 mail.setS_name(Sqltools.findusername(Integer.parseInt(id)));//收件人姓名
 mail.setP_name(cuser.getUsername());//發件人姓名
 mail.setP_id(cuser.getId());
 mail.setContent(content);
 mail.setTitle(zhuti);
 b = mb.addmailbox(mail);
 JSONObject obj = new JSONObject();
 obj.put("biaozhi", b);
 out = response.getWriter();
 out.write(obj.toString());
 }
 }
 /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
 @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 this.doGet(request, response);
 }
 }

二、DAO 介面與實作

介面只宣告必要的方法,讓控制層不依賴實作細節。

 package com.rc.dao;
 import java.util.List;
 import com.rc.entity.Mailbox;
 import com.rc.entity.TreeNodes;
 import com.rc.util.Page;
 public interface R_mailboxDAO {
 public List<Mailbox> getcostList(Page page); //獲取全部的郵件
 public int getcount();//獲取數目
 public boolean delete(Integer id); //刪除
 public boolean add(Mailbox mail);//寫信
 public boolean update(Integer id);//修改
 public List<TreeNodes> getnodes();//樹
 public boolean addmailbox(Mailbox mail);//添加郵件
 }

實作類中,分頁是靠 Oracle 的三層嵌套查詢搭配 rownum 完成的;寫信則以序列 mailbox_id_seq.nextval 產生主鍵,並預設「未發送」與「未讀取」兩個狀態位。

 package com.rc.daoimpl;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.List;
 import com.rc.dao.R_mailboxDAO;
 import com.rc.dbutil.Sqltools;
 import com.rc.entity.Mailbox;
 import com.rc.entity.TreeNodes;
 import com.rc.util.Page;
 import com.rc.util.StringUtil;
 public class R_mailboxDAOimpl implements R_mailboxDAO {
 boolean b=true;
 Connection cnn = null;
 PreparedStatement ps = null;
 ResultSet rs= null;
 Statement st = null;
 String sql="";
 @Override public List<Mailbox> getcostList(Page page) {
 List <Mailbox> mailboxlist = new ArrayList<Mailbox>();//定義一個數組
 int startsize = page.getCurrentPage()*page.getEverPage();
 int endsize = (page.getCurrentPage()-1)*page.getEverPage()+1;
 sql = "select * from (select a1.*,rownum rn from (select * from mailbox order by m_id desc) a1 WHERE rownum<="+startsize+") where rn>="+endsize+"";
 try{
 rs =Sqltools.excuteQuery(sql, null);
 while(rs.next()){
 Mailbox mailbox = new Mailbox();
 mailbox.setMid(rs.getInt("m_id"));
 mailbox.setP_name(rs.getString("p_name"));
 mailbox.setS_name(rs.getString("r_name"));
 mailbox.setStatus(rs.getString("r_status"));
 mailbox.setContent(rs.getString("r_content"));
 mailbox.setTitle(rs.getString("r_title"));
 mailbox.setR_time(StringUtil.TimetoString(rs.getDate("r_time")));
 mailboxlist.add(mailbox);
 }
 }catch(Exception e){
 Sqltools.close(rs, st, cnn);
 }
 return mailboxlist.size()==0 ? null:mailboxlist;
 }
 @Override public int getcount() {
 int count =0;
 sql = "select count(*) from mailbox";
 try{
 cnn = Sqltools.getConnection();
 ps = cnn.prepareStatement(sql);
 rs = ps.executeQuery();
 if(rs.next()){
 count = rs.getInt(1);
 }
 }catch(Exception e){
 e.printStackTrace();
 }finally{
 Sqltools.close(rs, ps, cnn);
 }
 return count;
 }
 @Override public boolean delete(Integer id) {
 sql="delete from mailbox where m_id=?";
 try{
 cnn=Sqltools.getConnection();
 ps=cnn.prepareStatement(sql);
 ps.setInt(1, id);
 ps.executeUpdate();
 }catch(Exception e){
 b=false;
 e.printStackTrace();
 }finally{
 Sqltools.aclose(rs, ps, cnn);
 }
 return b;
 }
 @Override public boolean add(Mailbox mail) {
 return false;
 }
 @Override public boolean update(Integer id) {
 return false;
 }
 @Override public List<TreeNodes> getnodes() {//得到樹節點
 String sql = "select * from tree_table order by nid ";
 cnn = Sqltools.getConnection();
 ArrayList<TreeNodes> treelist = new ArrayList<TreeNodes>();
 try {
 ps = cnn.prepareStatement(sql);
 rs =ps.executeQuery();
 while (rs.next()){
 TreeNodes node = new TreeNodes();
 node.setNid(rs.getInt("nid"));
 node.setParentId(rs.getInt("parentid"));
 node.setNodeName(rs.getString("nodename"));
 treelist.add(node);
 }
 } catch (SQLException e) {
 e.printStackTrace();
 }finally{
 Sqltools.aclose(rs, ps, cnn);
 }
 return treelist;
 }
 @Override public boolean addmailbox(Mailbox mail) {
 sql = "insert into mailbox(m_id,p_name,r_name,p_id,r_id,r_content,r_title,r_send,r_status,r_time) values(mailbox_id_seq.nextval,?,?,?,?,?,?,?,?,sysdate)";
 try{
 cnn =Sqltools.getConnection();
 ps = cnn.prepareStatement(sql);
 ps.setString(1,mail.getP_name());
 ps.setString(2,mail.getS_name());
 ps.setInt(3,mail.getP_id());
 ps.setInt(4,mail.getS_id());
 ps.setString(5,mail.getContent());
 ps.setString(6,mail.getTitle());
 ps.setString(7,"0");//是否發送
 ps.setString(8,"3");//是否讀取
 ps.executeUpdate();
 }catch(Exception e){
 b = false;
 e.printStackTrace();
 }finally{
 Sqltools.aclose(rs, ps, cnn);
 }
 return b;
 }
 }

三、JSP 頁面:Tab 分區與寫信彈窗

頁面上方用 nav-tabs 切出「郵件列表/未讀/已讀/草稿」四個分頁,每區各自有獨立 tbody 與分頁容器;「寫郵件」按鈕透過 data-toggle="modal" 開啟 Bootstrap 模態框,收件人欄位點擊後會展開 dTree 樹狀選單。

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
 <head>
 <base href="<%=basePath%>">
 <title>My JSP 'mailbox.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
 <head>
 <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/admin.css">
 <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/sweetalert.css">
 <link rel="stylesheet" type="text/css" href="/rccwgl/components/dtree/dtree.css">
 </head>
 <body>
 <!-- tab導航列表 -->
 <ul id="myTab" class="nav nav-tabs">
 <li class="active"><a href="#home" data-toggle="tab" class="btn btn-primary">郵件列表</a></li>
 <li><a href="#ios" data-toggle="tab" class="btn btn-success">未讀郵件</a></li>
 <li><a href="#gz" data-toggle="tab" class="btn btn-warning">已讀郵件</a></li>
 <li><a href="#cg" data-toggle="tab" class="btn btn-info">草稿列表</a></li>
 <li class="dropdown">
 <a href="#" id="myTabDrop1" class="dropdown-toggle btn-danger" data-toggle="dropdown">功能開發中 <b class="caret"></b>
 </a>
 <ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1">
 <li><a href="#jmeter" tabindex="-1" data-toggle="tab">開發一</a></li>
 <li><a href="#ejb" tabindex="-1" data-toggle="tab">開發二</a></li>
 </ul>
 </li>
 </ul>
 <!-- 郵件內容顯示 -->
 <div id="myTabContent" class="tab-content">
 <!-- 郵件列表 -->
 <div class="tab-pane fade in active" id="home">
 <div class="mainContent" >
 <input id="pl" type="button" class="btn btn-info" style="margin-top:50px;" onclick="pl()" value="批量刪除">
 <button class="btn btn-primary btn-bg pull-right" style="margin-top:50px;" data-toggle="modal" data-target="#myModal" onclick="addmail()">寫郵件</button>
 <div class="row">
 <div class="content">
 <table class="table table-hover table-bordered">
 <thead>
 <tr>
 <td align="left"><input type="checkbox" name="qx" onclick="quanxuan()" >全選</td>
 <td>主題</td>
 <td>發件人</td>
 <td>郵件內容</td>
 <td>接收時間</td>
 <td>是否讀取</td>
 <td>操作</td>
 </tr>
 </thead>
 <tbody id="list"></tbody>
 </table>
 <div id="pageinfo" style="height:200px;"></div>
 </div>
 </div>
 </div>
 </div>
 <!-- 未讀郵件 -->
 <div class="tab-pane fade" id="ios">
 <div class="mainContent" >
 <input type="submit" value="批量刪除" class="btn btn-info" style="margin-top:50px;">
 <input type="submit" value="寫郵件" class="btn btn-primary btn-bg pull-right" style="margin-top:50px;">
 <div class="row">
 <div class="content">
 <table class="table table-hover table-bordered">
 <thead>
 <tr>
 <td align="left"><input type="checkbox" name="qx" onclick="quanxuan(this)">全選</td>
 <td>序號</td>
 <td>發件人</td>
 <td>郵件內容</td>
 <td>接收時間</td>
 <td>是否讀取</td>
 <td>編輯</td>
 </tr>
 </thead>
 <tbody id="list1"></tbody>
 </table>
 <div id="pageinfo1" style="height:200px;"></div>
 </div>
 </div>
 </div>
 </div>
 <!-- 已讀郵件 -->
 <div class="tab-pane fade" id="gz">
 <div class="mainContent" >
 <input type="submit" value="批量刪除" class="btn btn-info" style="margin-top:50px;">
 <input type="submit" value="寫郵件" class="btn btn-primary btn-bg pull-right" style="margin-top:50px;">
 <div class="row">
 <div class="content">
 <table class="table table-hover table-bordered">
 <thead>
 <tr>
 <td align="left"><input type="checkbox" name="qx" onclick="quanxuan(this)">全選</td>
 <td>序號</td>
 <td>發件人</td>
 <td>郵件內容</td>
 <td>接收時間</td>
 <td>是否讀取</td>
 <td>編輯</td>
 </tr>
 </thead>
 <tbody id="list2"></tbody>
 </table>
 <div id="pageinfo2" style="height:200px;"></div>
 </div>
 </div>
 </div>
 <div class="tab-pane fade" id="jmeter">
 <div class="mainContent" >
 <p>jMeter 是一款開源的測試軟件。它是 100% 純 Java 應用程序,用於負載和性能測試。</p>
 </div>
 </div>
 <div class="tab-pane fade" id="ejb">
 <p>Enterprise Java Beans(EJB)是一個創建高度可擴展性和強大企業級應用程序的開發架構,部署在兼容應用程序服務器(比如 JBOSS、Web Logic 等)的 J2EE 上。 </p>
 </div>
 <!-- 草稿列表 -->
 <div class="tab-pane fade" id="cg">
 <div class="mainContent" >
 <input type="submit" value="批量刪除" class="btn btn-info" style="margin-top:50px;">
 <input type="submit" value="寫郵件" class="btn btn-primary btn-bg pull-right" style="margin-top:50px;">
 <div class="row">
 <div class="content">
 <table class="table table-hover table-bordered">
 <thead>
 <tr>
 <td align="left"><input type="checkbox" name="qx" onclick="quanxuan(this)">全選</td>
 <td>序號</td>
 <td>發件人</td>
 <td>郵件內容</td>
 <td>接收時間</td>
 <td>是否讀取</td>
 <td>編輯</td>
 </tr>
 </thead>
 <tbody id="list3"></tbody>
 </table>
 <div id="pageinfo3" style="height:200px;"></div>
 </div>
 </div>
 </div>
 </div>
 <!-- -->
 </div>
 <!-- 寫郵件的彈出框 -->
 <div id="alls" style="">
 <div class="container">
 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" >
 <div class="modal-dialog" role="document" style="width:800px">
 <div class="modal-content">
 <div class="modal-header">
 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
 <h4 class="modal-title" id="myModalLabel">寫郵件</h4>
 </div>
 <div class="modal-body">
 <div class="form-group">
 <label for="txt_departmentname">主題</label>
 <input type="text" name="txt_departmentname" class="form-control" id="zhuti" placeholder="部門名稱">
 </div>
 <div class="form-group">
 <div id="treediv" style="display:none;overflow:scroll; width: 150px;height:300px; padding: 5px;background: #fff;color: #fff;border: 1px solid #cccccc" >
 <input type="text" name="txt_parentdepartment" class="form-control" id="menu_parent_name">
 </div>
 </div>
 <div class="form-group">
 <label for="txt_departmentname">收件人</label>
 <input type="text" name="txt_departmentname" class="form-control" id="setvalue" placeholder="部門名稱">
 <input type="hidden" id="menu_parent" name="menu_parent"><!-- 父菜單id -->
 </div>
 <div class="form-group">
 <label for="txt_statu">郵件內容</label>
 <textarea rows="8" class="form-control" id="editor_id" name="content"></textarea>
 </div>
 </div>
 <div class="modal-footer">
 <button type="button" class="btn btn-success" id="send" data-dismiss="modal"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span>發送</button>
 <button type="button" class="btn btn-default" id="btn_close" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>關閉</button>
 <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存</button>
 </div>
 </div>
 </div>
 </div>
 </div>
 <script src="/rccwgl/js/jquery-3.1.0.min.js"></script>
 <script src="/rccwgl/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="js/bootstrap-paginator.js"></script>
 <script type="text/javascript" src="js/sweetalert.min.js"></script>
 <script type="text/javascript" src="js/sweetalert-dev.js"></script>
 <script src="/rccwgl/mailbox/js/mailbox.js"></script>
 <script type="text/javascript" charset="utf-8" src="mailbox/kindeditor-4.1.10/kindeditor.js"></script>
 <script charset="utf-8" src="mailbox/kindeditor-4.1.10/lang/zh_CN.js"></script>
 <script type="text/javascript" charset="utf-8" src="/rccwgl/mailbox/js//kdreply.js"></script>
 <SCRIPT type="text/javascript" src="/rccwgl/components/dtree/dtree.js"></SCRIPT>
 </body>
 </html>

四、前端腳本要點

分頁由 page1() 負責:先抓第一頁資料填進 tbody,再把 bootstrapPaginator 掛到容器上;使用者點頁碼時,onPageClicked 會清空 tbody 並重新請求,避免舊資料殘留造成視覺錯亂。刪除與批次刪除都先經 SweetAlert 二次確認,成功後清空清單再呼叫 page1() 重繪,而不是直接 reload 頁面,這樣才能保留提示動畫。

 $(function(){//初始化頁面
 page1();
 initTree();
 shouwtree();
 $('#treediv').mouseleave(function(){//在鼠標離開選擇樹的時候,選擇書影藏
 $("#treediv").hide();
 });
 });
 function Delete(mid){
 swal({ title: "你確定要進行該操作?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "是的, 刪除!", cancelButtonText: "不, 取消", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){
 if (isConfirm) {
 var action = "delete";
 $.ajax({ type : "post", url : "MailBoxServlet", datatype:'json', data:{action:action,id:mid,a:Math.random()}, success : function(data){
 var d= eval('('+data+')');
 if(d.biaozhi==true){ swal("刪除!", "刪除成功", "success");
 $("#list").empty();
 page1();
 }else{ swal("Deleted!", "刪除失敗", "error"); }
 }
 });
 } else { swal("", "你已經取消的該操作 ", "error"); }
 });
 }
 function Edit(mid){ alert(mid); }
 function pl(){//批量刪除
 var checkedList = new Array();
 if($("input[name='deleteCusersid']:checked").length>0){
 $("input[name='deleteCusersid']").each(function(){
 if($(this).prop("checked")){
 checkedList.push($(this).val());
 }
 });
 swal({ title: "你確定要刪除這"+checkedList.length+"行?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "是的, 確定刪除!", cancelButtonText: "不, 取消", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){
 if (isConfirm) {
 var action = "pldelete";
 $.ajax({ type : "post", url : "MailBoxServlet", datatype:'json', data:{action:action,a:Math.random(),deleteidlist:checkedList.toString()}, success : function(data){
 var d= eval('('+data+')');
 if(d.biaozhi==true){ swal("刪除!", "批量刪除成功", "success");
 $("input[name='deleteCusersid']").prop("checked",false);
 $("input[name='qx']").prop("checked",false);
 $("#list").empty();
 page1();
 }else{ swal("Deleted!", "刪除失敗", "error"); }
 }
 });
 } else {
 swal("", "你已經取消的該操作 ", "error");
 $("input[name='qx']").prop("checked",false);
 $("input[name='deleteCusersid']").prop("checked",false);
 }
 });
 }else{ swal("失敗!", "你必須選擇至少一行進行該操作!", "info"); }
 }
 function quanxuan(){//全選與全不選
 if($("input[name='qx']").prop("checked")){
 var checkbox = $("input[name='deleteCusersid']");
 checkbox.prop("checked",true);
 }else{
 var checkbox = $("input[name='deleteCusersid']");
 checkbox.prop("checked",false);
 }
 }
 function addmail(){//寫郵件
 $("#btn_submit").click(function(){
 var id = $("#menu_parent").val();
 var zhuti = $("#zhuti").val();//獲取主題
 var content = $("#editor_id").val();//獲取內容
 if(zhuti==""||id==""){
 if(zhuti==""){ swal("主題不能為空"); }else{ swal("收件人不能為空"); }
 return false;
 }else{
 var action = "save";
 $.ajax({ url: "MailBoxServlet", type : "post", data :{action:action,id :id,content :content,zhuti :zhuti,a : Math.random()}, success : function(data){
 if(data !=null){
 var d= eval('('+data+')');
 if(d.biaozhi){ swal("郵件編寫成功"); }else{ swal("郵件編寫失敗"); }
 }
 $("#zhuti").val("");
 $("#setvalue").val("");
 KindEditor.instances[0].html('');//專門的將textarea值置空
 $("#list").empty();
 page1();
 }
 });
 }
 $("#btn_close").click(function(){
 $("#zhuti").val("");
 $("#setvalue").val("");
 KindEditor.instances[0].html('');
 swal("關閉");
 });
 $("#send").click(function(){ swal("發送成功"); });
 }
 function initTree(){//初始化樹
 var action = "tree";
 mydtree = new dTree('mydtree','${pageContext.request.contextPath}/style/default/images/dtree/','no','no');
 mydtree.add(0, -1, "根目錄", "javascript:setvalue('0','根目錄')", "根目錄", "_self", true);
 $.ajax({ url: "MailBoxServlet", type : "post", data :{action:action,a : Math.random()}, success : function(data){
 if(data !=null){
 $.each(eval("(" +data+ ")").treelist,function(index,item){
 var id =item.nid; var pid = item.parentId; var nodesname = item.nodeName;
 mydtree.add(id,pid,nodesname,"javascript:setvalue('"+id+"','"+nodesname+"')",nodesname,"_self",false);
 });
 $("#treediv").html(mydtree.toString());
 }
 }
 });
 }
 function shouwtree(){
 $("#setvalue").click(function(){ $("#treediv").show(); });
 }
 function setvalue(id,name){
 $("#setvalue").val(name);
 $("#menu_parent").val(id);
 $("#treediv").hide();
 }
 function page1(){
 var pageNumber = 1;//默認初始頁為第一頁
 var action = "page";
 $.ajax({ url: "MailBoxServlet", type: "Post", data:{action:action,pageNumber:pageNumber,a:Math.random()}, success : function(data){
 if(data !=null){
 $.each(eval("(" + data + ")").mailbox, function (index, item) {
 var html = "<tr><td><input type='checkbox' name='deleteCusersid' value='"+item.mid+"'/></td><td>" + item.title + "</td><td>" + item.p_name + "</td><td>" + item.content + "</td><td>" +item.r_time+ "</td><td>" +item.status+ "</td><td>";
 m1 ="編輯"; m2="刪除";
 html2="<div class='btn-group'><button onclick='Edit("+item.mid+")' class='btn btn-info btn-sm' ><span class='glyphicon glyphicon-edit icon-white'></span> " +m1+"</button>" +"<button onclick='Delete("+item.mid+")' class='btn btn-danger btn-sm' ><span class='glyphicon glyphicon-trash icon-white'></span> " +m2+"</button>" +"</div></td></tr>";
 html+= html2;
 $("#list").append(html);
 });
 var pageCount = eval("(" + data + ")").Page[0].totalPage;
 var currentPage = eval("(" + data + ")").Page[0].currentPage;
 var options = {
 bootstrapMajorVersion: 2,
 currentPage: currentPage,
 totalPages: pageCount,
 itemTexts: function (type, page, current) {
 switch (type) {
 case "first": return "首頁";
 case "prev": return "上一頁";
 case "next": return "下一頁";
 case "last": return "末頁";
 case "page": return page;
 }
 },
 onPageClicked: function (event, originalEvent, type, page) {
 $("#list").empty();
 $.ajax({ url: "MailBoxServlet?pageNumber=" + page, type: "Post", data:{action:"page",a:Math.random()}, success: function (data1) {
 if (data1 != null) {
 $.each(eval("(" + data1 + ")").mailbox, function (index, item) {
 var html = "<tr><td><input type='checkbox' name='deleteCusersid' value='"+item.mid+"'/></td><td>" + item.mid + "</td><td>" + item.p_name + "</td><td>" + item.content + "</td><td>" +item.r_time+ "</td><td>" +item.status+ "</td><td>";
 m1 ="編輯"; m2="刪除";
 html2="<div class='btn-group'><button onclick='Edit("+item.mid+")' class='btn btn-info btn-sm' ><span class='glyphicon glyphicon-edit icon-white'></span> " +m1+"</button>" +"<button onclick='Delete("+item.mid+")' class='btn btn-danger btn-sm' ><span class='glyphicon glyphicon-trash icon-white'></span> " +m2+"</button>" +"</div></td></tr>";
 html+= html2;
 $("#list").append(html);
 });
 }
 }
 });
 }
 };
 $('#pageinfo').bootstrapPaginator(options);
 }
 });
 }

五、可以再加強的地方

原始碼裡有幾處值得留意:批次刪除目前是逐筆 delete,資料量大時應改為一條 IN 查詢;eval('('+data+')') 建議換成 JSON.parse 或 $.parseJSON;寫信成功後清空 KindEditor 要用 .html('') 而非 .val(''),否則編輯器內容不會被清掉。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved