Workflow: Grundsätzlich möchte ich die Anzahl der Pomodoro mit diesem Code aktualisieren: < /p>
backButton.addEventListener("click", async () => {
remainingPomodoro = Math.max(0, noPomodoros - (pomoCount - 1)); // Result clamped to 0
try {
const response = await fetch("/updatetask", {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({
taskId,
updatedpomoCount: remainingPomodoro
})
});
const rawText = await response.text();
try { // Read the response once
result = JSON.parse(rawText);
if (result.success) {
window.location.href = "/task-tracker";
}
else {
alert("Failed to update task.");
}
} catch (e) {
const text = await response.text();
console.error("Failed to parse JSON. Raw response:", text);
alert("Server error. Check console for details.");
return;
}
}
catch (error) {
console.error("Error updating task:", error);
alert("Error contacting server.");
}
< /code>
Dieser Code wird in Flask -Backend übertragen, um verarbeitet zu werden: < /p>
@app.route("/updatetask", methods=["POST"])
def updatetask():
if request.method == "POST":
data = request.get_json()
updated_pomocount = data.get("updatedpomoCount")
id = data.get("taskId")
db = get_db_connection()
cursor = db.cursor()
updated_task = cursor.execute("UPDATE tasks SET pomocount = ? WHERE id = ?", (updated_pomocount, id))
db.commit()
cursor.close()
db.close()
if updated_pomocount is None or id is None:
return jsonify({"success": False, "error": "Missing data"}), 400
return jsonify({"success": True})
< /code>
Ich habe jedoch diesen Fehler erhalten: < /p>
Fehleraktualisierungsaufgabe: TypeError: "Text" auf 'Antwort': Body Stream wurde bereits
bei htmlbuttonelement bereits ausgeführt. (pomodoro.js: 451: 41)
(anonym) @ pomodoro.js: 459 < /p>
< /blockquote>
Kann jemand jemandem helfen, die Grundursache des Problems zu identifizieren, warum ich das Problem in der ersten Stelle ausgelöst habe, um diesen Code zu beheben. Code < /p>
function addTask(taskName, noPomodoros, selectedDayIndex, taskId) {
console.log(taskName, noPomodoros, selectedDayIndex, taskId)
// Create a new task div
const taskDiv = document.createElement("div");
taskDiv.className = "task-div";
taskDiv.innerHTML =
`${taskName}
Pomodoros: ${noPomodoros}
delete`;
const deleteTaskButton = taskDiv.querySelector(".deleteTaskButton");
// Initially hide the button via CSS (not with inline style)
deleteTaskButton.style.opacity = "0";
deleteTaskButton.style.visibility = "hidden";
deleteTaskButton.style.transition = "all 0.3s ease;";
// Show button on hover (only for this taskDiv)
taskDiv.addEventListener("mouseenter", () => {
deleteTaskButton.style.opacity = "1";
deleteTaskButton.style.visibility = "visible";
});
taskDiv.addEventListener("mouseleave", () => {
deleteTaskButton.style.opacity = "0";
deleteTaskButton.style.visibility = "hidden";
});
// Add event listener to delete button
deleteTaskButton.addEventListener("click", async (e) => {
e.stopPropagation();
new Audio('/static/button-click.mp3').play()
try {
const response = await fetch ('/deletetask', {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
task_id : taskId,
}),
});
const result = await response.json();
if (result.success) {
taskDiv.remove();
alert("Task deleted successfully.");
} else {
alert("Failed to delete task.");
}}
catch (error) {
console.error("Error deleting task:", error);
alert("An error occurred.");
}
})
// Insert the task div into the correct column above the add task button
const targetColumn = document.querySelector(`.day-column[data-index="${selectedDayIndex}"]`)
const addButton = targetColumn.querySelector(".add-task");
targetColumn.insertBefore(taskDiv, addButton);
taskDiv.addEventListener("click", async () => {
const form = document.createElement("form");
form.method = "POST";
form.action = "/view-task";
const data = {
task_name: taskName,
no_pomodoros: noPomodoros,
day_idx: selectedDayIndex + 1,
};
for (const key in data) {
const input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
form.appendChild(input);
}
localStorage.setItem("currentTask", JSON.stringify({
taskName,
noPomodoros,
taskId,
day_idx: selectedDayIndex
}));
document.body.appendChild(form);
form.submit();
})
// Clear inputs and close popup
document.getElementById('taskNameInput').value = '';
document.getElementById('pomoCountInput').value = 1;
closeTaskPopup();
}
taskFormPopup.addEventListener("submit", async function (e) {
e.preventDefault(); // Prevent the form from submitting normally
const taskName = document.getElementById("taskNameInput").value.trim();
const noPomodoros = document.getElementById("pomoCountInput").value;
const taskDayIdx = parseInt(document.getElementById("dayIndexInput").value);
// Create a json object to send to flask serverside
const response = await fetch('/addtask', {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
task_name: taskName,
pomodoro_count: noPomodoros,
day_index: taskDayIdx,
}),
});
const data = await response.json();
console.log(data);
if (data.success) {
taskId = data.task_id;
addTask(taskName, noPomodoros, taskDayIdx, taskId);
alert("Task added successfully!");
}
else {
alert("Failed to add task. Please try again.")
}
})
< /code>
Die andere JavaScript -Datei empfängt dann die Informationen hier < /p>
const currentTask = JSON.parse(localStorage.getItem("currentTask"));
if (currentTask) {
taskId = currentTask.taskId;
noPomodoros = parseInt(currentTask.noPomodoros);
taskName = currentTask.taskName;
day_idx = currentTask.day_idx;
}
< /code>
Jede Art von Leitfaden und Hilfe wird geschätzt! Lassen Sie mich wissen, wenn Sie noch weitere Informationen benötigen.
JavaScript JSON Related TypeError ⇐ JavaScript
-
- Similar Topics
- Replies
- Views
- Last post