ASP.NET Core中Ajax延迟倒计时后计数器不更新问题求助
问题解决思路:前端倒计时同步更新方案
你当前的核心问题是:点击延迟按钮后,后端数据库已成功更新,但前端仍在使用页面加载时的初始剩余时间运行倒计时,没有同步最新的时间。除了重新渲染整个div,以下是两种更高效的解决方案:
方案一:后端返回更新后的时间,前端直接修改倒计时变量
这种方式依赖后端返回的准确时间,避免前后端系统时间差导致的误差。
1. 修改后端接口,返回更新后的剩余时间
在testedois控制器方法中,更新数据库后,计算并返回最新的剩余毫秒数:
// 假设已完成数据库更新逻辑,获取到更新后的WakeMe实体 var updatedWakeMe = _context.WakeMe.Find(id); updatedWakeMe.TimeToWake = updatedWakeMe.TimeToWake.AddSeconds(60); _context.SaveChanges(); // 计算并返回剩余毫秒数 var remainingMs = (updatedWakeMe.TimeToWake - DateTime.Now).TotalMilliseconds; return Json(new { success = "ok", remainingMilliseconds = remainingMs });
2. 前端调整代码,支持动态更新倒计时
把倒计时的核心变量(剩余时间、定时器实例)提到外层作用域,方便Ajax回调访问修改:
$(document).ready(function () { // 全局/外层变量,存储倒计时状态 let countdownTimer; let currentRemainingMs; let countdownContainer; // 初始化倒计时 $('div[id]').each(function () { countdownContainer = $(this); currentRemainingMs = parseInt(countdownContainer.attr("id")); countdownTimer = setInterval(function () { currentRemainingMs -= 1000; // 时间格式化逻辑(原代码不变) const h = Math.floor(currentRemainingMs / 3600000); const m = Math.floor((currentRemainingMs - h * 3600000) / 60000); const s = Math.floor((currentRemainingMs - h * 3600000 - m * 60000) / 1000); const formattedM = m < 10 ? `0${m}` : `${m}`; const formattedS = s < 10 ? `0${s}` : `${s}`; $('.remain', countdownContainer).html(`${h}:${formattedM}:${formattedS}`); }, 1000); }); // 延迟按钮点击事件 $('#btn').click(function () { $.ajax({ url: '/home/testedois', type: 'POST', dataType: 'json', data: { id: 1, segundos: 60 }, }) .done(function (data) { if (data.success === 'ok') { // 用后端返回的准确剩余时间更新变量 currentRemainingMs = data.remainingMilliseconds; } }) .fail(function () { console.log("请求失败"); }); }); });
方案二:前端先本地更新,再同步后端(提升用户体验)
这种方式让用户立刻看到倒计时变化,再异步同步后端,失败时回滚时间,兼顾体验和数据一致性:
$(document).ready(function () { let countdownTimer; let currentRemainingMs; let countdownContainer; // 初始化倒计时(代码同方案一) $('div[id]').each(function () { // ... 省略初始化逻辑 }); $('#btn').click(function () { // 先本地更新,用户立刻看到延迟效果 const addMs = 60 * 1000; currentRemainingMs += addMs; // 异步同步后端 $.ajax({ url: '/home/testedois', type: 'POST', dataType: 'json', data: { id: 1, segundos: 60 }, }) .done(function (data) { if (data.success !== 'ok') { // 后端更新失败,回滚时间 currentRemainingMs -= addMs; alert('延迟失败,请重试'); } }) .fail(function () { // 请求失败,回滚时间 currentRemainingMs -= addMs; console.log("请求失败"); }); }); });
内容的提问来源于stack exchange,提问作者Claudinei Ferreira
相关产品推荐
相关产品推荐

