目前,引入了 JSON 来处理请求表单。我已经不止一次地编写了课程中解释的代码,并且我有 99% 的信心我确实正确地编写了所有内容。但当我尝试使用请求表单时,我总是收到错误“405 method not allowed”。网上搜索没有得到任何结果,我找不到解决我的问题的方法。下面是它应该运行的 python 路线: @app.route('/todos/create', methods=['POST']) def create_todo(): description = request.get_json()['description'] todo = Todo(description=description) db.session.add(todo) db.session.commit() return jsonify({ 'description': todo.description })这里是 HTML 脚本 <script> document.getElementById('form').onsubmit = function(e){ e.preventDefault(); fetch('/todos/create', { method: 'POST', body: JSON.stringify({ 'description': document.getElementById('description').value }), headers: { 'Content-Type': 'application/json' } }) .then(function(response){ return response.json(); }) .then(function(jsonResponse){ console.log(jsonResponse); const lil_item = document.createElement('LI'); lil_item.innerHTML = jsonResponse['description']; document.getElementById('todos').appendChild(lil_item); }); } </script>我希望有人能帮助我,我真的不知道如何解决这个问题。提前致谢。
1 回答
白板的微信
TA贡献1883条经验 获得超3个赞
在您的 html 文档中,表单对象没有 id。在 javascript 代码中,您正在查找 id = "form" 的对象上的提交事件,但这样的元素不存在。
所以你只需要改变:
<form id="myForm" method="post"> <input type="text" id="description" name="description" /> <input type="submit" name="Create" /> </form>
然后在JS中:
document.getElementById('myForm').onsubmit = ...添加回答
举报
0/150
提交
取消
