在我的项目中,我使用Python Flask作为服务器端,JS作为前端。该项目允许用户选择一张照片并使用 AJAX post 方法将照片发送到服务器端。服务器端会对这张照片进行图像处理,并将图像的一些数据以JSON格式返回给前端。
JS代码如下:
$(document).ready(function(){
$("form").submit(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/upload',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: false,
success: function(result) {
var ctx = document.getElementById("result").getContext("2d");
res = JSON.parse(result)
var data = {
labels: res['sentiment'],
datasets: [
{
label: "Face Analysis",
fillColor: "white",
data: res['score']
}
]
};
var myLineChart = new Chart(ctx).Bar(data, {
showScale: false
});
},
});
return false; // so that form doesn't try to complete post
});
});
对我来说有一个令人困惑的地方,最后一行 return false
,它的作用是什么?如果我删除这一行,应用程序将失败。我从其他资源找到这个,虽然后面有评论,但还是不明白意思?
Flask 路线如下:
@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
#print "post method"
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('uploaded_file',filename=filename))
result = image_analysis(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print type(result)
return json.dumps({'sentiment':result.keys(),'score':result.values()})
#return json.dumps({'aftervalue':"baoqger"})
最佳答案
如果单击提交按钮,浏览器将提交带有提交按钮的表单,除非在返回 false
的流程中执行了 javascript 函数。 .
这样做的最初目的是为了验证:
(a) user enters data and clicks submit,
(b) js code is run to do form validation,
(c) form submit is prevented if validation code returnedfalse
.
当然,我们现在有了 Ajax,它可以自行提交或执行其他魔法。 return false;
可能永远都需要防止浏览器自行执行(另一个)提交。
类似的行为存在于例如超链接:如果 <a href
onclick 事件返回 false,然后单击超链接将运行 js,但不会导航到该链接。
关于Jquery和Flask : how to understand the 'return false' in form submit function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912090/