我想添加一個包含刪除按鈕的div列表元素,並在添加後刪除它。當我嘗試在添加該div後立即刪除該div元素時,它將其從html中刪除,但不會從服務器端刪除。刷新頁面時,我看到該元素,並且可以在刷新頁面後將其刪除。我的代碼如下。我使用ajax.post方法發送服務器,並使用jquery post方法刪除。jQuery用ajax Post方法追加和刪除元素
$(function() {
$("button#formDepartment").click(function(){
$.ajax({
type: "POST",
url: "addsomething.php",
data: $('form#newDepartment').serialize(),
success: function(data) {
document.getElementById("newDepartment").reset();
idDep = data;
},
error: function(){
alert("failure");
}
});
var departmentName = $('#nameDepartment').val();
var newDepartmentElem =
' <div class="list-group-item" data-plugin="editlist"> \
<div class="list-content"> \
<span class="list-text">' + departmentName + '</span> \
<div class="item-actions"> \
<span class="btn btn-pure btn-icon" id="deleteDepartment" data-delete-id="' + idDep + '" ><i class="icon wb-trash" aria-hidden="true"></i></span> \
</div> \
</div> \
</div>';
$(newDepartmentElem).hide().appendTo("#departmentList").slideDown('slow');
});
$(document).on('click', 'span#deleteDepartment', function() {
var deleteId = $(this).data("delete-id");
var removeItem = $(this).closest('.list-group-item');
bootbox.dialog({
message: "this department will be deleted.",
title: "Delete department",
buttons: {
success: {
label: "Delete",
className: "btn-success",
callback: function() {
$.post("deletesomething.php",
{itemId : deleteId, deleteItem : "department"}
);
removeItem.slideUp(600);
toastr.error("Department deleted.");
console.log(deleteId);
}
},
danger: {
label: "Cancel",
className: "btn-danger",
callback: function() {
}
}
}
});
});
});
檢查你的後端代碼,這個問題是存在的! –
沒有它的作品。我可以從其他頁面使用它。我想我知道問題在哪裏,但我不知道如何解決。也許你可以幫忙。在我的代碼中,我添加了帶有混合參數data-delete-id的新html div,因爲它無法找到data-id並且無法發送到服務器。爲了解決這個問題,我嘗試了一個全局變量,它包含了ajax.post成功回調函數中的id。但它不起作用。我無法將該變量添加到我的代碼中。如何在成功回調函數中創建一個全局變量? –
當你插入時,你在某處返回'id'?或不 ! –