基于jQuery的测验模块时限到后无法自动提交问题求助
Hey there! Let's figure out why your 30-minute quiz auto-submit isn't triggering when the timer runs out. Based on the code snippets you shared, here are the most likely issues and fixes to check:
1. Verify the End Time Calculation
First up, let's make sure your end time is being calculated correctly:
- The function name
get15dayFromNowis confusing (it suggests 15 days instead of 30 minutes!)—double-check that this is just a typo and doesn't mess up the underlying logic. - Confirm that
<?php echo $duration ; ?>outputs the number30in your rendered HTML. Right-click the page, view source, and look for this line—if it's outputting something else (like0or a string), your PHP variable is the problem. - Test the function directly in your browser's console: run
console.log(get15dayFromNow())and check if it returns a date/time exactly 30 minutes from the current moment.
2. Ensure the Countdown Plugin's Expiry Callback is Set
It looks like you're using a jQuery countdown plugin, but you didn't include the full code for it. Most countdown plugins require an expiry/finish callback to trigger actions when time runs out. Here's how to set it up correctly:
function getEndTime() { return new Date(new Date().valueOf() + <?php echo $duration ; ?> * 60 * 1000); } var $time_spend = $('#time_spend'); $time_spend.countdown(getEndTime(), function(event) { // Update your countdown display here (e.g., using event.strftime('%H:%M:%S')) }).on('finish.countdown', function() { // This is where the auto-submit happens! // Replace '#quiz-form' with your actual quiz form ID/class $('#quiz-form').submit(); });
If you missed the finish.countdown event listener, that's almost certainly why the submit isn't firing.
3. Add a Fallback Timer for Background Tabs
Browsers often throttle timers in inactive background tabs, which can break countdown plugins. Add a simple interval check as a safety net:
var endTime = getEndTime(); var submitChecker = setInterval(function() { if (new Date() >= endTime) { $('#quiz-form').submit(); clearInterval(submitChecker); // Stop checking once submitted } }, 10000); // Check every 10 seconds
This ensures the form submits even if the plugin fails due to browser throttling.
4. Check for JavaScript Errors
Open your browser's developer tools (F12 → Console tab) and look for any errors. Common issues here include:
- The countdown plugin isn't loaded (look for "undefined" errors related to
.countdown()). - Your form selector is incorrect (e.g., wrong ID/class for the quiz form).
- Variables like
$durationaren't being passed correctly from PHP.
5. Confirm Form Submission Logic Works
Test the submit function manually first—run $('#quiz-form').submit() in the console and see if the form submits as expected. If it doesn't, there might be other issues (like form validation blocking submission, or a missing action attribute on the form).
内容的提问来源于stack exchange,提问作者Ansh

