如何通过HTML按钮删除JSON文件中指定index的对象?
Solution to Delete JSON Object and Sync with File
First, let's fix a critical issue: your original JSON file has invalid syntax (two top-level objects). We need to wrap them in an array to make it valid. Here's the corrected data.json:
[ { "data": [{ "index": "1", "part": "15", "dueDate": "2019-03-19" }] }, { "data": [{ "index": "2", "part": "22", "dueDate": "2019-03-19" }] } ]
Next, we'll implement the full delete workflow that updates both the DOM and the JSON file.
Step 1: Frontend (HTML/JavaScript)
We'll add a function to send delete requests to PHP, and refresh the data after success.
HTML (assuming your data container exists):
<div id="data-container"></div>
JavaScript:
// Load and render data on page load function loadData() { fetch('load-data.php') .then(res => res.json()) .then(data => { const container = document.getElementById('data-container'); container.innerHTML = ''; data.forEach(item => { const { index, part, dueDate } = item.data[0]; const itemDiv = document.createElement('div'); itemDiv.className = 'data-item'; itemDiv.innerHTML = ` <p>Index: ${index} | Part: ${part} | Due Date: ${dueDate}</p> <button class="delete-btn" data-index="${index}">Delete</button> `; container.appendChild(itemDiv); }); // Bind delete events after rendering attachDeleteListeners(); }) .catch(err => console.error('Failed to load data:', err)); } // Attach click events to delete buttons function attachDeleteListeners() { document.querySelectorAll('.delete-btn').forEach(btn => { btn.addEventListener('click', function() { const targetIndex = this.dataset.index; deleteItem(targetIndex); }); }); } // Send delete request to backend function deleteItem(index) { fetch('delete-item.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `index=${encodeURIComponent(index)}` }) .then(res => res.json()) .then(result => { if (result.success) { loadData(); // Refresh data to reflect changes alert(`Item with index ${index} deleted successfully!`); } else { alert(`Error: ${result.message}`); } }) .catch(err => console.error('Delete request failed:', err)); } // Initialize on page load window.addEventListener('load', loadData);
Step 2: Backend (PHP)
We'll create two PHP files: one to load data, and another to handle deletions.
load-data.php (reads JSON and returns data):
<?php $jsonPath = 'data.json'; if (!file_exists($jsonPath)) { http_response_code(404); echo json_encode(['success' => false, 'message' => 'Data file not found']); exit; } $jsonContent = file_get_contents($jsonPath); $data = json_decode($jsonContent, true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Invalid JSON in data file']); exit; } header('Content-Type: application/json'); echo json_encode($data); ?>
delete-item.php (handles deletion and updates JSON):
<?php $jsonPath = 'data.json'; // Validate request method if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Only POST requests allowed']); exit; } // Check for index parameter if (!isset($_POST['index'])) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Missing "index" parameter']); exit; } $targetIndex = $_POST['index']; // Load and parse JSON if (!file_exists($jsonPath)) { http_response_code(404); echo json_encode(['success' => false, 'message' => 'Data file not found']); exit; } $jsonContent = file_get_contents($jsonPath); $data = json_decode($jsonContent, true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Failed to parse JSON']); exit; } // Filter out the item to delete $updatedData = []; $itemFound = false; foreach ($data as $item) { if ($item['data'][0]['index'] !== $targetIndex) { $updatedData[] = $item; } else { $itemFound = true; } } if (!$itemFound) { http_response_code(404); echo json_encode(['success' => false, 'message' => 'Item with specified index not found']); exit; } // Write updated data back to file if (file_put_contents($jsonPath, json_encode($updatedData, JSON_PRETTY_PRINT))) { echo json_encode(['success' => true, 'message' => 'Item deleted']); } else { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Failed to update data file (check file permissions)']); } ?>
Key Notes:
- File Permissions: Make sure your web server has write access to
data.json(chmod 644 or similar depending on your setup). - Error Handling: The code includes basic error handling for common issues like missing files, invalid JSON, and missing parameters.
- Data Sync: By reloading data after deletion, we ensure the DOM always matches the JSON file content.
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

