当后端返回save JSON的success为true时,如何实现页面刷新?
Solution for Auto-Refresh on Successful Form Submission
Your backend controller logic is already set up correctly to return the right JSON responses. We just need to update your frontend AJAX code to handle those responses and trigger a page refresh when the save succeeds.
Here's the modified view code with comments explaining the new parts:
$(document).on('submit', '#creationOptionsForm', function(e){ e.preventDefault(); var form_data = new FormData($('#creationOptionsForm')[0]); var formURL = $(this).attr("action"); $.ajax({ url: formURL, processData: false, contentType: false, async: false, // Note: Using async: false is deprecated in jQuery; consider switching to async: true if possible cache: false, type: "POST", data: form_data }) // Handle successful AJAX response (request reached server) .done(function(response) { // jQuery auto-parses JSON if backend sends the correct Content-Type header if (response.success) { // Refresh the page immediately when save is successful location.reload(); } else { // Optional: Display backend error messages to the user console.error("Save failed:", response.messages); // Example: Show errors in a dedicated UI element // $('#errorContainer').text(JSON.stringify(response.messages)).removeClass('hidden'); } }) // Handle AJAX-level errors (network issues, server crashes, etc.) .fail(function(jqXHR, textStatus, errorThrown) { console.error("Request failed:", textStatus, errorThrown); // Optional: Show a generic error alert to users // alert("Oops, something went wrong. Please try again later."); }); });
Key Changes Explained:
- Added
.done()handler: This runs when the AJAX request reaches the server successfully (even if the save failed, it just means we got a valid JSON response). - Page refresh trigger: When
response.successistrue, we calllocation.reload()to refresh the page automatically. - Error handling: The
.fail()handler catches issues like network timeouts or server errors, so you can inform users of unexpected problems. - Optional error display: You can uncomment the example lines to show the specific validation errors from your backend in the UI, which helps users correct their input.
Quick Note on async: false:
Using async: false blocks the entire browser until the request finishes, which can make your page feel unresponsive. If you don't have a strict requirement to keep it, switch to async: true—the rest of the code will work just as well since we're using asynchronous handlers.
内容的提问来源于stack exchange,提问作者AbdulMUTIMF
相关产品推荐
相关产品推荐

