jQuery.Timer结合Ajax提交多表单值:仅按钮触发存DB的需求调整
调整jQuery.Timer的保存逻辑:仅点击按钮时保存时长和备注
Hey there! Let's tweak this setup so we only save the timer's data when that "Save Time & Notes" button gets clicked, instead of auto-saving on every stop/restart. Here's a straightforward approach tailored to your needs:
Step 1: Update Your HTML
First, make sure your save button and notes input are set up (adjust IDs to match your existing markup if needed):
<div id="timer-display"></div> <button id="save-timer-btn">保存时间和备注</button> <textarea id="timer-notes" placeholder="添加备注..."></textarea>
Step 2: Modify the JavaScript
We'll ditch the auto-save on timer stop/restart, and instead bind the save action directly to your button click. Just make sure you reference your existing timer instance correctly:
// 假设这是你已有的定时器初始化代码 var myTimer = $('#timer-display').timer({ format: '%H:%M:%S', // 其他你需要的配置项... }); // 给保存按钮绑定点击事件 $('#save-timer-btn').on('click', function() { // 获取定时器当前累计时长(根据jQuery.Timer版本调整方法) // 大部分版本用`getTimer()`获取毫秒数,转成秒更适合数据库存储 var totalSeconds = Math.floor(myTimer.timer('getTimer') / 1000); // 获取用户输入的备注 var userNotes = $('#timer-notes').val().trim(); // 发送AJAX请求到后端保存 $.ajax({ url: 'save-timer.php', // 替换成你的后端处理页面路径 method: 'POST', data: { duration: totalSeconds, notes: userNotes }, success: function(response) { alert('时间和备注已成功保存!'); $('#timer-notes').val(''); // 清空备注框 }, error: function(xhr, status, err) { console.error('保存出错:', err); alert('保存失败,请稍后重试。'); } }); });
Step 3: Backend PHP (save-timer.php)
Here's a simple, secure example of handling the POST request and saving to your database (use prepared statements to avoid SQL injection):
<?php // 连接你的数据库(替换成你的数据库信息) $dbHost = 'localhost'; $dbName = 'your_database'; $dbUser = 'your_username'; $dbPass = 'your_password'; try { $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 获取前端传来的参数 $duration = $_POST['duration']; $notes = $_POST['notes']; // 插入数据到数据库 $stmt = $pdo->prepare("INSERT INTO timer_logs (duration_seconds, notes, created_at) VALUES (?, ?, NOW())"); $stmt->execute([$duration, $notes]); echo '保存成功'; } catch(PDOException $e) { die('数据库错误: ' . $e->getMessage()); } ?>
Quick Reminders:
- Remove old auto-save code: Be sure to delete any existing AJAX calls that were triggered by the timer's
onStoporonStartevents—we don't need those anymore. - Check jQuery.Timer API: If
getTimer()doesn't work for your plugin version, check the docs—some versions usegetElapsedTime()or expose asecondsproperty directly on the timer instance. - Add validation: For production, add server-side checks (e.g., ensure
durationis a positive number, sanitizenotesto prevent XSS).
内容的提问来源于stack exchange,提问作者Burndog
相关产品推荐
相关产品推荐

