通过JavaScript调用Flask的render_template无法跳转页面问题
问题原因
你用fetch发送的是AJAX异步请求,这种请求的特性就是在后台和服务器交互,不会自动触发页面跳转。哪怕Flask返回了200状态码和evidence.html的内容,浏览器也只会默默接收这些HTML,不会主动跳转到新页面。
解决方法
给你两种实用的处理方案,按需选择:
方案1:改用表单提交(最简单,适合单纯跳转场景)
如果你的需求只是点击按钮后跳转到新页面,完全没必要用AJAX,直接用HTML表单包裹按钮就行:
<!-- 给每个按钮套个表单 --> <form action="/full_evidence/{{ query_content }}" method="POST"> <button type="submit" class="evd-btn" value="{{ array_id }}">查看完整证据</button> </form>
点击按钮时,浏览器会直接提交表单,服务器返回evidence.html后就会自动跳转。
方案2:保留AJAX,手动处理页面跳转/内容替换
如果必须用AJAX(比如跳转前要做额外逻辑),可以按以下方式修改:
子方案A:让Flask返回重定向,前端手动跳转
先修改Flask路由,POST请求处理完后重定向到GET请求(浏览器会识别重定向并跳转):
from flask import redirect, url_for, session @app.route('/full_evidence/<query>', methods=['GET', 'POST']) def full_evidence(query): if request.method == 'POST': content = retriever.get_source(query) # 把获取到的内容存入session,供GET请求渲染页面用 session['evidence_content'] = content # 重定向到同一个路由的GET请求 return redirect(url_for('full_evidence', query=query)) # GET请求时,从session取出内容传给模板 content = session.get('evidence_content') return render_template('evidence.html', content=content)
然后前端修改fetch逻辑,处理重定向响应:
container.addEventListener('click', event => { const tgt = event.target.closest(".evd-btn"); if (!tgt) return; // 过滤非按钮点击事件 let arrayID = tgt.value; const arrayInt = Number(arrayID); const queryArray = mesgArray[arrayInt]; fetch("/full_evidence/"+queryArray, {method: "POST"}) .then(response => { // 如果是重定向响应,直接跳转到目标URL if (response.redirected) { window.location.href = response.url; } }) .catch(err => console.error('请求出错:', err)); });
子方案B:直接用返回的HTML替换当前页面内容
如果不想跳转页面,只是替换当前页面的部分或全部内容:
container.addEventListener('click', event => { const tgt = event.target.closest(".evd-btn"); if (!tgt) return; let arrayID = tgt.value; const arrayInt = Number(arrayID); const queryArray = mesgArray[arrayInt]; fetch("/full_evidence/"+queryArray, {method: "POST"}) .then(response => response.text()) // 把响应转为HTML文本 .then(html => { // 替换整个页面内容 document.body.innerHTML = html; // 或者只替换指定容器:document.getElementById('main-content').innerHTML = html; }) .catch(err => console.error('请求出错:', err)); });
内容的提问来源于stack exchange,提问作者user1753640
相关产品推荐
相关产品推荐

