1. 程式人生 > >Ajax實現動態顯示並操作表資訊

Ajax實現動態顯示並操作表資訊

在jsp連線資料庫訪問並顯示資料庫資訊時,使用Ajax利用json物件會在頁面不重新整理的情況下獲取到資料。但若是要顯示資料庫表中的資訊,就需要動態的生成表的行以及單元格。並且對每一行的操作也是需要動態繫結的。

今天分享給各位的是完成在對資料庫表資訊的顯示、增加、刪除、修改。顯示時通過用HTML程式碼來控制table行的增加。修改和刪除是通過button的onclick()事件完成的。onclick()的引數也是動態改變的,這樣的話在操作時就可以知道是要對哪一行進行操作了。修改的方法中又用到修改HTML程式碼使普通<td>變為<input>並獲取到原始值作為輸入框的預設值,在輸入框失去焦點後自動儲存資料。並再把<input>變為<td>

程式碼很詳細,希望能對你有所幫助。

js檔案內容如下:

$(function () {
    $.ajaxSetup({
        async:false
    });
        var url = "/Task/Fenlei";        //servlet的url
        data = {};
        data.flag = "all";
    $.post(url,data,function (result) {
        for(var i=0;i<result.getAll.length;i++){
            var id = result.getAll[i].fenlei_Id;
            var name = result.getAll[i].fenlei_Name;
            var newrow = "<tr id='tr"+id+"'><td>"+result.getAll[i].fenlei_Id+"</td><td id='td"+id+"'>"+result.getAll[i].fenlei_Name+
                "</td><td><button onclick='del("+id+")''>刪除</button><button onclick='edit("+id+")'>修改</button></td></tr>"
            $("#AllInfo tr:last").after(newrow);
        }
    },"json");
        $("#add").click(function () {
            addData={};
            var name = $("#name").val();
            addData.name = name;
            addData.flag = "add";
            $.post(url,addData,function (result) {
                var id = result.aFenlei.fenlei_Id;
                var name = result.aFenlei.fenlei_Name;
                    var newrow = "<tr id='tr"+id+"'><td>"+result.aFenlei.fenlei_Id+"</td><td id='td"+id+"'>"+result.aFenlei.fenlei_Name+
                        "</td><td><button onclick='del("+id+")'>刪除</button><button onclick='edit("+id+")'>修改</button></td></tr>"
                    $("#AllInfo tr:last").after(newrow);
                

            },"json");
        });
});
function del(id) {
    console.log(id);
    var url = "/Task/Fenlei";
    delData = {};
    delData.flag = "delete";
    delData.id = id;
    $.post(url,delData,function (result) {
         if(result) {
             alert("刪除成功");
             $("#tr"+id).remove();
         } else {
             alert("刪除失敗");
         }
    },"json");
};
function edit(id) {
    var url = "/Task/Fenlei";
    editData = {};
    editData.flag = "update";
    var oldname = $("#td"+id).text();
    $("#td"+id).html("<input type='text'class='Input' id='new' name='FenleiName' value='"+oldname+"'/>");
    $("#new").blur(function () {
        var newname = $(".Input").val();
        editData.newname = newname;
        console.log(newname);
        $("#td"+id).html("<td id='td"+id+"'>"+newname+"</td>");
        $.post(url,editData,function(result){
            if(result) {
                alert("修改成功");
            } else {
                alert("修改失敗");
            }
        },"json");
    });
}
jsp頁面程式碼如下:
<%@include file="../inc/top.jsp"%>
<script src="Fenlei.js"></script>
<div class="Classify">
    <h3 align="center">專案管理資訊表</h3>
    <div class="divBack">
        <img src="#" />
    </div>
    <div class="divAdd">
    分類名稱:<input type="text" id="name"/>
    <button type="button" class="btn-primary" id="add">新增</button>
     </div>
    <table class="table"id="AllInfo">
        <tr>
            <th>分類Id</th>
            <th>分類名稱</th>
            <th>操作</th>
        </tr>
    </table>
</div>
<%@include file="../inc/bottom.jsp"%>
處理的servlet內容如下:
public class FenleiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");         //專案分類名稱
        String flag = request.getParameter("flag");
        String id = request.getParameter("id");             //專案分類Id
        FenleiService cs = new FenleiService();
        JSONObject json = new JSONObject();
        if("all".equals(flag)) {
            List<FenleiBean> list = cs.getAll();            //獲取所有的專案分類資訊
            json.put("getAll",list);
            response.getWriter().print(json.toJSONString());
        }
        if("add".equals(flag)) {            //增加操作。
            FenleiBean cb = cs.add(name);
            json.put("aFenlei",cb);
            response.getWriter().print(json.toJSONString());
        }
        if("delete".equals(flag)) {         //刪除操作
             boolean result = cs.delete(id);
            System.out.println(flag);
            System.out.println(result);
            if(result){
                json.put("result",result);
                json.put("msg","刪除成功");
                response.getWriter().print(json.toJSONString());
                System.out.println(json.toJSONString());
            } else {
                json.put("result",result);
                json.put("msg","刪除失敗");
                response.getWriter().print(json.toJSONString());
            }
        }
        if("update".equals(flag)) {       //更新資訊
            System.out.println(flag);
            String newname = request.getParameter("newname");
            System.out.println("---------------update newname"+newname);
            boolean result = cs.update(newname);
            if(result){
                json.put("result",result);
                json.put("msg","修改成功");
                response.getWriter().print(json.toJSONString());
                System.out.println(json.toJSONString());
            } else {
                json.put("result",result);
                json.put("msg","修改失敗");
                response.getWriter().print(json.toJSONString());
            }
        }
    }
}
</pre><pre name="code" class="javascript">