Flask Ajax请求后不要重新加载网页 [英] Don't reload webpage after flask ajax request
问题描述
我有这个ajax请求
$(function() {
$('#left').bind('click', function() {
var form = $('form#data')[0]; //
var formData = new FormData(form);
$.ajax({
url: "{{ url_for('encode') }}",
type: 'POST',
data: formData,
async: false,
success: function (data) {
$("#img-2").attr("src", "{{url_for('static', filename='encoded.png')}}");
$("#diff").show();
},
cache: false,
contentType: false,
processData: false
});
});
});
当单击按钮时,此烧瓶功能运行.
And this flask function runs when the button is clicked.
@app.route('/encode', methods=['GET', 'POST'])
def encode():
a = request.form['text']
img = request.files['files']
img.save("./static/original.png")
secret = lsb.hide(img, a)
secret.save("./static/encoded.png")
return "ok"
我遇到的问题是该网页转了一秒钟,因为它应该设置图像并显示diff按钮.但是之后,该网页将重新加载并重置为索引页.而且我真的不知道如何防止这种情况的发生.我在做什么错了?
The problem I am having is that the webpage becomes for a split second as it should be the image is set and the button diff is shown. But after that the webpage reloads and resets to the index page. And I do not really know how to prevent that from happening. What am I doing wrong?
推荐答案
盲目猜测:您的button
可能是表单的一部分,因此单击时的默认行为是提交表单并重新加载页面.您可以使用event.preventDefault()
来防止这种情况:
Blind guess : your button
may be part of a form, so its default behaviour when clicked is to submit the form and reload the page. You can prevent that by using event.preventDefault()
:
$('#left').bind('click', function(event) {
event.preventDefault()
......
这篇关于Flask Ajax请求后不要重新加载网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!