gpt4 book ai didi

Javascript foreach循环多次调用ajax

转载 作者:行者123 更新时间:2023-11-28 03:14:51 25 4
gpt4 key购买 nike

所以我正在尝试创建包含多个面板的待办事项列表。每个板都有添加项目按钮。如果我单击“添加项目”按钮,它将打开插入任务信息的模式。但是,如果我多次单击“添加项目”按钮,然后将信息插入模式并按“保存 ajax”,则会触发我单击“添加项目”按钮的次数。我怎样才能防止这种情况发生?

var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function(addNewItem) {
addNewItem.addEventListener("click", function(e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");

addNewBtn.addEventListener ("click", function(e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;


$.ajax({
type: "POST",
url: "add.php",
data: { content: contentValue , title: titleValue , listid: boardId },

success: function(data, textStatus, jqXHR) {

$("#todoItems-" + id + "").append(data);

}
});

});
});
});



最佳答案

您可以使用一个变量(例如busy)来验证 AJAX 请求是否已在进行。

您可以在 AJAx 的 beforeSend 回调中设置此变量,然后在 finally 回调中将其更新回 false:

var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function (addNewItem) {
addNewItem.addEventListener("click", function (e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");

var busy = false;

addNewBtn.addEventListener("click", function (e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;

if (!busy) {
$.ajax({
type: "POST",
url: "add.php",
beforeSend: () => {
busy = true;
}
data: {
content: contentValue,
title: titleValue,
listid: boardId
},
success: function (data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
},
complete: () => {
busy = false;
}
});
}
});
});
});

这是一个非常简单的解决方案,但它确实有效。

关于Javascript foreach循环多次调用ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com