如何将LocalStorage存储的数据POST提交到Flask的@app.route路由?
LocalStorage数据提交Flask后端实现方案
核心逻辑:LocalStorage是浏览器端本地存储,Flask后端无法直接读取,必须在前端发起POST请求前把存储的用户名注入到请求参数中,随表单一起提交。
1. 调整HTML表单结构
在现有表单中新增一个隐藏输入框,专门承载从LocalStorage读取的用户名,表单提交时会自动携带该字段值,不需要改动原有表单提交逻辑:
注意:建议把getname()事件绑定在form的submit事件上,不要绑在提交按钮的click事件上,能避免事件触发时机晚于表单提交、导致用户名字段漏传的问题。
<div class="posting"> <h5>Write Something & Post!</h5> <form method="POST" action="/authenticate/post" autocomplete="off" onsubmit="getname()"> <textarea class="books" placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea> <!-- 新增隐藏字段,对用户不可见 --> <input type="hidden" name="username" id="username-field"> <br><br> <input id="enter" type="submit" class="books" value="Post!"> </form> </div>
2. 完善前端JS逻辑
修改现有getname()函数,把从LocalStorage拿到的用户名赋值给隐藏字段,保证提交时值已经存在:
function getname() { // 读取LocalStorage中的用户名,做兜底处理避免null值 const username = localStorage.getItem('username') ?? ''; // 把值写入表单隐藏字段 document.getElementById('username-field').value = username; // 不需要额外写提交代码,赋值完成后表单会自动按原有逻辑提交 }
3. 修改Flask后端接收逻辑
后端从表单参数中读取新增的username字段即可,建议用get()方法取值并设置默认值,避免字段不存在时抛出KeyError:
@app.route("/authenticate/post", methods=['GET', 'POST']) def posting(): if request.method == 'POST': # 用get方法取值,缺省的时候给默认值,不会触发KeyError报错 post_content = request.form.get('post', '') username = request.form.get('username', '匿名用户') # 后续可自行编写业务逻辑,比如把用户名和帖子内容绑定存入数据库 return render_template("testing.html", post=post_content, username=username) # GET请求直接返回发帖页面 return render_template("index.html")
可选:异步无刷新提交方案
如果需要提交后不刷新页面,可以去掉原生表单提交逻辑,用fetch手动构造请求发送:
function getname(e) { // 阻止表单默认跳转提交 e.preventDefault(); const username = localStorage.getItem('username') ?? ''; const postContent = document.getElementById('post').value; // 构造表单请求体 const fd = new FormData(); fd.append('post', postContent); fd.append('username', username); // 发起POST请求 fetch('/authenticate/post', { method: 'POST', body: fd }).then(resp => resp.text()) .then(resHtml => { // 处理返回结果,比如把返回的页面内容渲染到当前页 document.documentElement.innerHTML = resHtml; }) }
内容的提问来源于stack exchange,提问作者Bedazzling TRUES
相关产品推荐
相关产品推荐

