【发布时间】:2021-09-26 22:27:17
【问题描述】:
我正在编写一个 Flask 应用程序,我希望能够使用表单将信息输入数据库而无需刷新页面。 这是我的表格:
<form id="vocab_form">
<label for="name">Word:</label>
<input type="text" id="word" name="word">
<label for="def">Definition</label>
<input type="text" id="def" name="def">
<input type="submit" value="Add Term">
</form>
这是我用来发送请求的脚本。它嵌入在包含表单的 html 文件中。
<script>
$(document).on('submit', '#vocab_form', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/',
data:{
word:$(#word).val(),
def:$(#def).val()
},
success:function(){
alert('success');
}
})
});
这是我发送表单数据的路径。它调用另一个文件中的函数将数据输入到我的数据库中,并在线收集一些信息来呈现页面。
@app.route("/", methods=["GET", "POST"])
def hello():
if request.method == "POST":
word = request.form["word"]
definition = request.form["def"]
query.add_word(word, definition)
message="Word added successfully! {} means {}".format(word, definition)
else:
message="no form data"
wordlist=query.get_all_words()
lines = web_functions.get_les_mis()
return render_template("home.html", message=message, wordlist=wordlist, lines=lines)
虽然我的脚本包含防止表单默认提交行为的指令,但每次我提交表单时页面都会重新加载。我想防止这种情况。任何建议或见解将不胜感激!
【问题讨论】:
-
浏览器控制台有错误吗?这可能会阻止脚本运行
-
如果你确实检查了控制台,我想你会看到一个错误,因为
$(#word)应该是$("#word")- 你忘记了引号。在下一行相同。投票结束是一个错字。
标签: javascript python ajax flask