求助:JavaScript实现5分钟文章自动更新失败,Flask文章切换问题
我来帮你搞定这个问题!看起来你已经在后端用Flask搞定了RSS源的抓取,现在卡在前端自动切换和定时更新的部分对吧?下面分步骤给你解决:
第一步:完善后端Flask代码,统一数据格式
首先得把三个RSS源的文章整理成前端好处理的统一格式,避免字段混乱。补全你的路由代码:
from flask import Flask, render_template, jsonify import feedparser app = Flask(__name__) def get_articles(): articles = [] # 定义要抓取的RSS源列表 rss_sources = [ "https://feeds.feedburner.com/OffshoreEnergyToday?format=xml", "http://feeds.feedburner.com/OffshoreWindNews?format=xml", "你的第三个RSS源地址" # 把这里替换成你实际的第三个源 ] for source in rss_sources: try: feed = feedparser.parse(source) # 每个源取前3篇,可按需调整数量 for entry in feed.entries[:3]: # 兼容不同RSS源的图片字段(有的是media_content,有的是enclosure) article_image = "" if "media_content" in entry: article_image = entry.media_content[0].get("url", "") elif "enclosure" in entry: article_image = entry.enclosure.get("url", "") articles.append({ "title": entry.title, "image": article_image, "content": entry.summary }) except Exception as e: print(f"抓取{source}失败:{str(e)}") continue return articles @app.route('/test') def hello_world(): articles = get_articles() return render_template('article_template.html', articles=articles) # 新增API接口,用于前端无刷新获取最新文章 @app.route('/api/articles') def articles_api(): articles = get_articles() return jsonify(articles) if __name__ == '__main__': app.run(debug=True)
第二步:前端模板实现自动切换+定时更新
接下来写article_template.html,实现两个核心功能:定时切换已有文章、每5分钟从后端拉取最新内容。
<!DOCTYPE html> <html> <head> <title>自动更新文章</title> <style> .article-card { max-width: 800px; margin: 2rem auto; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .article-title { margin-top: 0; color: #2d3748; } .article-image { width: 100%; height: auto; border-radius: 4px; margin: 1rem 0; } .article-content { color: #4a5568; line-height: 1.6; } </style> </head> <body> <div class="article-card" id="articleCard"> <h2 class="article-title" id="articleTitle">{{ articles[0].title }}</h2> {% if articles[0].image %} <img src="{{ articles[0].image }}" alt="文章配图" class="article-image" id="articleImage"> {% endif %} <div class="article-content" id="articleContent">{{ articles[0].content|safe }}</div> </div> <script> // 初始化文章数据和索引 let articles = {{ articles|tojson }}; let currentArticleIndex = 0; const interval = 5 * 60 * 1000; // 5分钟,单位毫秒 let switchTimer; let refreshTimer; // 更新页面显示当前文章 function updateArticleDisplay() { const titleEl = document.getElementById('articleTitle'); const imageEl = document.getElementById('articleImage'); const contentEl = document.getElementById('articleContent'); const currentArticle = articles[currentArticleIndex]; titleEl.textContent = currentArticle.title; if (currentArticle.image) { imageEl.src = currentArticle.image; imageEl.style.display = 'block'; } else { imageEl.style.display = 'none'; } contentEl.innerHTML = currentArticle.content; } // 切换到下一篇文章 function switchToNextArticle() { currentArticleIndex = (currentArticleIndex + 1) % articles.length; updateArticleDisplay(); } // 从后端刷新最新文章列表 async function refreshArticleList() { try { const response = await fetch('/api/articles'); const newArticles = await response.json(); // 只有当新文章和旧文章数量/内容不同时才更新 if (JSON.stringify(newArticles) !== JSON.stringify(articles)) { articles = newArticles; currentArticleIndex = 0; updateArticleDisplay(); } } catch (err) { console.error('刷新文章失败:', err); } } // 启动定时器 function startTimers() { // 每5分钟切换一篇文章 switchTimer = setInterval(switchToNextArticle, interval); // 每5分钟刷新一次后端数据 refreshTimer = setInterval(refreshArticleList, interval); } // 页面加载完成后启动定时器 window.addEventListener('load', startTimers); // 页面隐藏时暂停定时器,节省资源 document.addEventListener('visibilitychange', () => { if (document.hidden) { clearInterval(switchTimer); clearInterval(refreshTimer); } else { startTimers(); } }); </script> </body> </html>
第三步:关键优化说明
- 无刷新更新:用
/api/articles接口返回JSON数据,避免整页刷新,提升用户体验 - 错误容错:后端抓取RSS源时加了try-except,单个源出错不会影响整个页面
- 资源优化:页面隐藏时暂停定时器,减少不必要的请求和DOM操作
- 字段兼容:处理了不同RSS源的图片字段差异,避免图片显示失败
这样就能实现你想要的:每5分钟自动切换一篇文章,同时同步拉取最新的RSS内容更新列表啦!
内容的提问来源于stack exchange,提问作者NibSjors
相关产品推荐
相关产品推荐

