使用jQuery与AJAX删除记录失效:刷新后数据恢复问题求助
Hey there! No worries at all—learning web dev with Java and AJAX always comes with these little gotchas, so let’s work through this together.
First, let’s figure out why your records are "coming back" after refresh: your AJAX request isn’t actually sending the necessary IDs (assetId and batchId) to your backend, so the database never gets the command to delete the record. The "disappearance" you see is just the frontend removing the row without updating the database, hence it reappears on refresh.
Do you need to add language identifiers and IDs to the AJAX URL?
- For the IDs (
assetId,batchId): Absolutely—these are critical for your backend to know which record to delete. You can pass them either in the request body (via thedataproperty in AJAX, which is more standard for POST requests) or as URL path parameters (e.g.,opname/cancel/{assetId}/{batchId}if your backend uses REST-style routing). - For the language identifier: Only if your backend needs it (e.g., to return localized error messages). If your app doesn’t handle multi-language yet, you can skip it for now.
Step-by-step fixes for your code
1. First, make sure you’re capturing the correct IDs
Before calling cancelOpname, you need to set assetId and batchId from your UI (e.g., when the user clicks the delete button). For example:
// Attach click event to your delete confirmation button $('.delete-confirm-btn').click(function() { // Get IDs from data attributes on the record row (adjust selectors to match your UI) assetId = $(this).closest('.record-row').data('asset-id'); batchId = $(this).closest('.record-row').data('batch-id'); // Show your confirmation modal here, then call cancelOpname when user clicks "Yes" });
2. Fix the AJAX request to send IDs and handle responses correctly
Your original code has a few key issues:
- The
datavariable is undefined (you need to pass the IDs here) - The
successcallback uses the outerdatavariable instead of the actual AJAX response window.history.back()takes you to the previous cached page, which won’t show the updated database state
Here’s the corrected code:
var assetId; var batchId; function cancelOpname(){ $.ajax({ type: "POST", cache: false, url: urlPage + "opname/cancel", dataType: "JSON", // Send IDs (and language if needed) in the request body data: { assetId: assetId, batchId: batchId, // lang: $('html').attr('lang') // uncomment if you need language support }, beforeSend: function() { $('.loader').fadeIn(); }, complete: function() { $('.loader').fadeOut(); }, // Use `response` instead of the outer `data` for the AJAX result success: function(response) { if (!response.errorResult) { console.log("Delete successful!"); // Instead of going back, refresh the page to load updated data location.reload(); // OR if you don't want a full refresh, re-fetch and re-render your record list // loadOpnameRecords(); } else { console.log("Delete failed: ", response.errorMessage); alert("删除失败,请检查后重试"); // Show user-friendly error } }, error : function(e) { console.log("AJAX Error Details: ", e); alert("请求出错,请检查网络连接或联系管理员"); } }); }
3. Ensure your backend handles the request correctly
On your Java Eclipse side, make sure your controller is receiving the IDs and executing the delete properly (example using Spring):
// Example Spring Controller method (adjust based on your framework) @PostMapping("/opname/cancel") @ResponseBody public Map<String, Object> cancelOpname(@RequestParam("assetId") Long assetId, @RequestParam("batchId") Long batchId) { Map<String, Object> response = new HashMap<>(); try { // Execute your delete query using assetId and batchId opnameService.deleteRecord(assetId, batchId); response.put("errorResult", false); } catch (Exception e) { response.put("errorResult", true); response.put("errorMessage", e.getMessage()); // Log the error for debugging e.printStackTrace(); } return response; }
Key Takeaways
- Always send unique identifiers (like
assetId/batchId) with your delete request—without them, the backend can’t target the right record. - Avoid
window.history.back()after updates; instead, refresh the page or re-fetch data to ensure you’re showing the latest database state. - Double-check that your backend actually commits the delete operation (make sure transactions are set up correctly if you’re using them).
内容的提问来源于stack exchange,提问作者Julham Ramadhana

