【发布时间】:2020-04-07 16:30:03
【问题描述】:
我使用 AJAX 获取方法将此表单提交到烧瓶应用程序,但由于某种原因它没有通过服务器,我可以提醒输入没有问题。
<html>
<head>
<title>TODO App</title>
</head>
<style>
.hidden {
display: none;
}
</style>
<body>
<form id="form" >
<input type="text" id="description" name="description" />
<input type="submit" value="Create" />
</form>
<div id="error" class="hidden">Something went wrong</div>
<uL id="todos">
{%for d in data%}
<li>{{d.description}}</li>
{%endfor%}
</uL>
</body>
<script>
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
//alert(document.getElementById('description').value);
let desc = document.getElementById('description').value;
alert(desc);
fetch('/todos/create', {
method: 'POST',
body: JSON.stringify({
'description': desc
}),
headers: {
'content-type': 'application/json'
}
})
.then(function (response){
return response.json();
})
.then(function(jsonResponse){
console.log(jsonResponse);
const liItem = document.createElement('LI');
liItem.innerHTML = jsonResponse['description'];
document.getElementById('todos').appendChild(liItem);
})
.catch(function(){
document.getElementById('error').className = '';
})
}
</script>
</html>
如果需要,python 函数会监听这个:
@app.route('/todos/create', methods=['POST'])
def create_todo():
#description = request.form.get('description', '')
description = request.form.get_json()['description']
todo = Todo(description=description)
db.session.add(todo)
db.session.commit()
#return redirect(url_for('index'))
return jsonfiy({
'description' : todo.description
})
带有 id = description 的文本输入是有问题的,我总是收到 catch 中指定的错误消息。不确定是什么问题 !当python函数具有默认值以防字段未填充时,项目将被添加到数据库中没有问题,但是当我删除默认值时出现问题,因为输入没有传递到服务器
【问题讨论】:
-
您可以尝试通过 Postman 之类的方式拨打电话以检查它是否正常工作吗?
-
我认为你应该使用 request.get_json() 而不是 request.form.get_json()
-
请尝试
body: {'description': desc}和description = request.form['description']
标签: javascript ajax asynchronous fetch