Flask Modal确认弹窗提交后如何获取表单内的用户输入数据
解决方案
问题原因
你当前的写法中,Modal 里的确认按钮绑定的是独立的空表单,没有携带原页面表单里用户输入的标题、评论数据,所以后端无法拿到对应输入值。
最简修改方案(无需调整后端代码,仅修改前端模板)
只需要让 Modal 的确认按钮直接提交原输入表单即可,修改 post.html 代码如下:
- 给原表单添加唯一ID,把原提交按钮改为普通按钮(避免点击时直接提交表单,只保留弹窗功能)
<!-- 原表单添加id属性,去掉method后的多余逗号 --> <form id="postForm" action="" method="POST" enctype="multipart/form-data"> {{ form.hidden_tag() }} <p></p> <h4>New Post</h4> <div class="form-group"> {{ form.title_field.label(class="form-control-label") }} {{ form.title_field(class="form-control form-control-lg") }} </div> <div class="form-group"> {{ form.comment_field.label(class="form-control-label") }} {{ form.comment_field(class="form-control form-control-lg") }} </div> <!-- 给原提交按钮添加type="button",避免直接触发表单提交 --> {{ form.submit( class="btn btn-outline-info", type="button", data_toggle="modal", data_target="#updateModal") }} </form>
- 修改Modal部分,删除确认按钮外层的独立表单,添加点击事件触发原表单提交
<!-- Modal --> <div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="updateModalLabel">New Post?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <!-- 如果需要预览输入内容,可以添加modal-body展示 --> <!-- <div class="modal-body"> 确认提交以下内容?<br> 标题:<span id="previewTitle"></span><br> 评论:<span id="previewComment"></span> </div> --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <!-- 删除原来的独立form,给确认按钮加id --> <button type="button" class="btn btn-success" id="confirmSubmit">Confirm</button> </div> </div> </div> </div> <!-- 添加JS逻辑 --> <script> // 点击确认按钮提交原表单 document.getElementById('confirmSubmit').addEventListener('click', function() { document.getElementById('postForm').submit(); }); // 如果需要预览内容,添加以下代码,弹窗打开时同步输入值 /* document.getElementById('updateModal').addEventListener('show.bs.modal', function () { const title = document.querySelector('input[name="title_field"]').value; const comment = document.querySelector('textarea[name="comment_field"]').value; document.getElementById('previewTitle').textContent = title; document.getElementById('previewComment').textContent = comment; }) */ </script>
修改完成后,点击Modal的确认按钮就会直接提交带用户输入的原表单,后端路由里的 form.title_field.data 和 form.comment_field.data 可以正常拿到输入值,不需要调整原有后端逻辑。
内容的提问来源于stack exchange,提问作者jackpot
相关产品推荐
相关产品推荐

