You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript待办应用中移除已完成任务(需用XMLHttpRequest)

Solution: Delete All Completed Tasks with XMLHttpRequest

Got it, let's walk through how to build a one-click solution to delete all tasks marked as completed (where active is "false") using XMLHttpRequest. We'll cover both the frontend button/interaction and a backend example to update your JSON data.


1. Frontend: Add the Button & XHR Logic

First, add a button to your view to trigger the deletion, then write the JavaScript to handle the request and update the UI.

HTML

<button id="deleteCompletedBtn">Delete All Completed Tasks</button>
<div id="taskContainer"><!-- Your existing task list will render here --></div>

JavaScript

// Attach click handler to the delete button
document.getElementById('deleteCompletedBtn').addEventListener('click', function() {
  // Optional: Confirm with user before deleting
  if (!confirm('Are you sure you want to remove all completed tasks?')) {
    return;
  }

  // Initialize XMLHttpRequest
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/remove-completed-tasks', true); // Replace with your backend endpoint
  xhr.setRequestHeader('Content-Type', 'application/json');

  // Handle successful response
  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      const updatedTaskData = JSON.parse(xhr.responseText);
      // Refresh the task list in your view
      refreshTaskView(updatedTaskData.list);
      alert('All completed tasks deleted successfully!');
    } else {
      alert('Oops, something went wrong deleting tasks.');
    }
  };

  // Handle network errors
  xhr.onerror = function() {
    alert('Network error occurred. Please check your connection.');
  };

  // Send the request (we can pass a simple action flag if needed)
  xhr.send(JSON.stringify({ action: 'delete-completed' }));
});

// Helper function to render tasks (adjust to match your existing view structure)
function refreshTaskView(tasks) {
  const container = document.getElementById('taskContainer');
  container.innerHTML = '';

  tasks.forEach(task => {
    const taskItem = document.createElement('div');
    taskItem.className = task.active === 'false' ? 'task completed' : 'task';
    taskItem.innerHTML = `
      <h4>${task.name}</h4>
      <p>${task.desc}</p>
      <small>Added: ${task.date}</small>
    `;
    container.appendChild(taskItem);
  });
}

2. Backend: Update the JSON File

Next, you need a backend endpoint to receive the request, filter out completed tasks, and save the updated data back to your JSON file. Here's an example using Node.js/Express:

Step 1: Setup Dependencies

npm install express

Step 2: Server Code

const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
app.use(express.json());

// Endpoint to handle deleting completed tasks
app.post('/remove-completed-tasks', (req, res) => {
  const taskFilePath = path.join(__dirname, 'tasks.json'); // Path to your JSON file

  // Read current task data
  fs.readFile(taskFilePath, 'utf8', (readErr, data) => {
    if (readErr) {
      console.error(readErr);
      return res.status(500).json({ error: 'Failed to load task data' });
    }

    try {
      const taskData = JSON.parse(data);
      // Filter out tasks where active is "false"
      taskData.list = taskData.list.filter(task => task.active !== 'false');

      // Save updated data back to JSON file
      fs.writeFile(taskFilePath, JSON.stringify(taskData, null, 2), 'utf8', (writeErr) => {
        if (writeErr) {
          console.error(writeErr);
          return res.status(500).json({ error: 'Failed to save updated tasks' });
        }
        // Send updated task list back to frontend
        res.json(taskData);
      });
    } catch (parseErr) {
      console.error(parseErr);
      res.status(400).json({ error: 'Invalid JSON data in task file' });
    }
  });
});

// Serve your frontend files (HTML/JS/CSS)
app.use(express.static(path.join(__dirname, 'public')));

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Key Notes to Keep in Mind

  • Endpoint Matching: Ensure the URL in xhr.open() matches your backend endpoint exactly.
  • String vs Boolean: Your JSON uses string values for active ("false"/"true"), so the filter checks for task.active !== 'false' (not the boolean false).
  • UI Refresh: The refreshTaskView function updates your frontend after deletion—tweak it to match your existing task rendering logic.
  • Error Handling: Added basic error handling for network issues, file read/write failures, and invalid JSON.

内容的提问来源于stack exchange,提问作者ceki10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:13:31