DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
Ajax 留言板加上淡出刪除效果:從主鍵回傳到事件重新綁定
編輯:AJAX詳解     

上一篇文章我們做了一個 Ajax 留言板,這次把它升級成可以刪除留言的版本,並同步更新資料庫。成品效果可以參考 https://www.CSS88.com/demo/Ajax-delete/,差別只在於我們真的會把資料從資料庫移除。

第一步:新增留言時把主鍵回傳

要刪除資料庫中的指定資料,一定要有主鍵值,否則資料庫不知道該刪哪一列。所以留言新增成功後,必須把剛寫入的 id 回傳,並寫進 DOM,刪除時才拿得到。後端的 MessageAdd 方法因此要調整成這樣:

/// <summary>
/// 新增留言
/// </summary>
private void MessageAdd(Message message, HttpContext context)
{
    SQLHelper helper = new SQLHelper();
    string cmdText = "INSERT INTO TB_MESSAGE_BOARD(MSG_USER, MSG_CONTENT, MSG_FACE, MSG_TIME) VALUES('"
        + message.Msg_nickname + "','"
        + message.Msg_content + "','"
        + message.Msg_face + "','"
        + message.Msg_time + "')";

    if (helper.RunSQL(cmdText, null))
    {
        // 取出剛剛插入的 id
        DataTable dt = helper.getDataTable(
            "select top 1 msg_id from TB_MESSAGE_BOARD order by MSG_TIME desc");
        context.Response.Write(dt.Rows[0]["msg_id"].ToString());
    }
    else
    {
        context.Response.Write("-1");
    }
}

前台操作 DOM 的地方也要跟著改,把回傳的 id 設成新元素的 id:

$.ajax({
    type: "POST",
    url: "Ajax/MessageBoardHandler.ashx?action=add",
    data: "msg_nickname=" + escape(msg_nickname)
        + "&msg_content=" + escape(msg_content)
        + "&msg_time=" + msg_time
        + "&msg_face=" + msg_face,
    success: function (msg) {
        if (msg != "-1") {
            $('#messagelist').append(
                "<div class='box clearfix' id='" + msg + "'>"
                + "<img src='" + msg_face + "' width='50' height='50' class='avatar' />"
                + "<div class='text'><strong><a href='#'>" + msg_nickname + "</a></strong>"
                + "<p>" + msg_content + "</p>"
                + "<div class='date'>" + msg_time + "</div></div>"
                + "<a href='#' class='delete'>x</a></div>");
            $('.delete').bind("click", s);
        }
    }
});

第二步:刪除邏輯

後端收到 id 後直接下 DELETE 指令,成功回 success,失敗回 fail:

/// <summary>
/// 刪除留言
/// </summary>
private void MessageDel(string id, HttpContext context)
{
    SQLHelper helper = new SQLHelper();
    string cmdText = "delete from TB_MESSAGE_BOARD where msg_id='" + id + "'";

    if (helper.RunSQL(cmdText, null))
        context.Response.Write("success");
    else
        context.Response.Write("fail");
}

前台的 JavaScript 則負責確認框、動畫與請求:

$(".delete").click(function s() {
    var commentContainer = $(this).parent();
    $(".question").hide();               // 先收掉其他已開啟的確認框

    var id = commentContainer.attr("id"); // 取得留言 id
    var param = 'id=' + id;

    $(this).after(
        '<div class="question">你確定刪除該評論嗎?<br/>'
        + '<span class="yes">確定</span><span class="cancel">取消</span></div>');
    $(this).next('.question').animate({ opacity: 1 }, 300);

    $('.yes').bind('click', function () {
        $.ajax({
            type: "POST",
            url: "Ajax/MessageBoardHandler.ashx?action=del",
            data: param,
            cache: false,
            success: function () {
                commentContainer.slideUp('slow', function () {
                    commentContainer.remove();
                });
            }
        });
        return false;
    });

    $('.cancel').bind('click', function () {
        $(this).parents('.question').fadeOut(300, function () {
            $(this).remove();
        });
    });
});

兩個實務上的提醒

第一,動態新增的留言雖然 class 也叫 delete,但它的 click 事件不會自動生效,必須重新綁定一次:$('.delete').bind("click", s);。這是 jQuery 事件委派機制造成的常見困惑,改用 on() 做事件委派可以少掉這一步。

第二,原範例有個 bug:連續點不同留言的刪除圖示時,會跳出好幾個確認框。程式中 $(".question").hide() 那一行就是為了修掉它——每次開新確認框前,先把其他的一律收起來。

另外提醒,範例中的 SQL 是字串拼接寫法,實際專案請改用參數化查詢,避免 SQL injection 風險。

完成後的效果如下,刪除時帶有漸變與滑動動畫:

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