Flask中/handleClick路由无法跳转至渲染的test.html页面求助
问题原因
你用**AJAX(XMLHttpRequest)**发送请求时,浏览器只是在后台悄悄接收服务器返回的test.html内容,不会自动跳转或打开新页面,所以你看不到test.html加载,网络面板里只会显示/handleClick的请求(因为test.html是作为这个请求的响应内容返回的,不是单独的请求)。
解决方案
根据你“打开test.html页面”的需求,推荐两种处理方式:
方式1:直接跳转页面(最符合需求)
放弃AJAX,直接通过页面跳转的方式发送请求,这样浏览器会主动加载服务器返回的test.html页面。修改sendData函数:
<script> function sendData(event){ const clickedCard = event.target.closest('.small_card'); const title = clickedCard.querySelector('.labels h2').textContent; // 直接跳转到目标路由并携带参数 window.location.href = '/handleClick?title=' + encodeURIComponent(title); } </script>
点击卡片后,浏览器会发起新的页面请求,服务器渲染test.html并返回,页面就会自动切换到test.html。
方式2:用AJAX加载内容到当前页面(不跳转)
如果不想跳转页面,只想在当前页面展示test.html的内容,可以在XHR的回调中处理返回的HTML:
- 在index.html中添加一个容器用于展示内容:
<div id="page-content"></div>
- 修改JavaScript代码,接收服务器返回的HTML并插入到容器中:
<script> function sendData(event){ const clickedCard = event.target.closest('.small_card'); const title = clickedCard.querySelector('.labels h2').textContent; var xhr = new XMLHttpRequest(); xhr.open('GET', '/handleClick?title=' + encodeURIComponent(title), true); // 添加回调处理响应内容 xhr.onload = function() { if (xhr.status === 200) { // 将返回的test.html内容插入到指定容器 document.getElementById('page-content').innerHTML = xhr.responseText; } }; xhr.send(); } </script>
额外验证点
- 确保
test.html放在Flask项目的templates文件夹下,路径正确; - 检查路由函数中
render_template('test.html')的文件名拼写是否正确,大小写是否匹配(部分操作系统区分文件名大小写)。
内容的提问来源于stack exchange,提问作者Imran Alam
相关产品推荐
相关产品推荐

