Python Flask表单数据存入数据库全为NULL问题求助
解决Flask表单提交后数据库存入NULL的问题
嗨,我看了你的代码,问题核心是前端数据没有正确传递到后端——毕竟你硬编码能成功,说明Flask的数据库连接和插入逻辑是没问题的,咱们一步步来修复:
1. HTML表单缺少name属性
Flask的request.form.get()是通过input的name属性来取值的,不是id。你的input只有id没有name,后端自然拿不到任何值,最终数据库就只能存入NULL。
修正后的HTML代码:
<form method="POST"> <p>ID of your Avenger:</p> <input type="number" id="ID" name="ID" required> <p>Name of your Avenger:</p> <input type="text" id="name" name="name" required> <p>Post Code of your Avenger:</p> <input type="text" id="postcode" name="postcode" required> <p>Date of Birth of your Avenger:</p> <input type="date" id="dateofbirth" name="dateofbirth" required> <p>Bank balance of your Avenger:</p> <input type="number" id="balance" name="balance" required> <p>Description of your Avenger:</p> <input type="text" id="description" name="description" required> <button class="button1" type="button" id="hashButton" onclick="nameInput()">Submit</button> </form>
(给每个input都加上和id一致的name属性即可)
2. JavaScript获取和传递数据的方式错误
document.getElementById()只能接收单个元素ID作为参数,你一次性传多个是无效的,只会返回第一个元素(ID)的value,其他字段的值根本没拿到。另外,发送的数据格式也不符合x-www-form-urlencoded的要求。
修正后的JavaScript代码:
function nameInput() { // 逐个获取每个字段的输入值 const id = document.getElementById("ID").value; const name = document.getElementById("name").value; const postcode = document.getElementById("postcode").value; const dateofbirth = document.getElementById("dateofbirth").value; const balance = document.getElementById("balance").value; const description = document.getElementById("description").value; // 拼接成符合要求的urlencoded格式字符串,用encodeURIComponent处理特殊字符 const formData = `ID=${id}&name=${encodeURIComponent(name)}&postcode=${encodeURIComponent(postcode)}&dateofbirth=${dateofbirth}&balance=${balance}&description=${encodeURIComponent(description)}`; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { const json = JSON.parse(this.responseText); document.getElementById("nameInputReturn").innerHTML = json.name; } } xhttp.open("POST", "http://127.0.0.1:5000/sendData", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(formData); // 发送拼接好的完整表单数据 }
3. 可选优化:用FormData简化代码
如果你觉得手动拼接字符串太麻烦,可以用浏览器原生的FormData对象自动收集表单数据,更简洁不易出错:
function nameInput() { // 获取页面中的表单元素 const form = document.querySelector('form'); // 自动收集所有带name属性的input值 const formData = new FormData(form); const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { const json = JSON.parse(this.responseText); document.getElementById("nameInputReturn").innerHTML = json.name; } } xhttp.open("POST", "http://127.0.0.1:5000/sendData", true); // 使用FormData时无需手动设置Content-Type,浏览器会自动处理 xhttp.send(formData); }
最后再确认下:你的Flask代码里conn和cursor的初始化应该是没问题的(毕竟硬编码能成功),修复完前端的问题后,点击提交就能正确把数据存入数据库啦!
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

