在AJAX调用后,HTML页面无法从Flask呈现

时间:2019-03-23 19:03:29

标签: javascript python ajax flask

我想发送一个JavaScript变量,其中包含用户将上传到我的Flask文件中要进行处理的图像的图像。所以我使用Formdata和AJAX调用相同。但是在烧瓶中接收到数据和图像并完成处理后,我无法在烧瓶中呈现HTML页面,该页面将显示已处理的图像。

Java脚本代码:

formdata = new FormData();      
jQuery("#image_to_upload").on("change", function() {     // On Change Of image upload
    var file = this.files[0];
    if (formdata) {
        formdata.append("file", file);
        formdata.append("array", filtersActive);
        jQuery.ajax({
            url: "/object-detect-uploader",   
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success:function(){}
        });
    }                       
});

烧瓶代码:

@app.route("/object-detect-uploader", methods = ['GET', 'POST'])
def upload_object_detection():
    detect_objs = request.values['array'].split(",")

    d_array= [0 for i in range(6) ]
    for i in detect_objs:
        d_array[int(i)] = 1
    for upload in request.files.getlist("file"):
        filename = upload.filename
        # This is to verify files are supported
        ext = os.path.splitext(filename)[1]
        if (ext == ".jpg") or (ext == ".png"): #File extention check
            print("File supported moving on...")
            ans=(object_detection_module.object_detection(upload,d_array))
        else:
            render_template("Error.html", message="Files uploaded are not supported...")
    print("Rendering")
    return render_template("index.html", result = ans)

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <br>
    <br>
<h1><center>Output</h1></center>
<br> 
<img src="data:image/png;base64,  {{result[0]}}" >
<br>
<br>
<h2> No of objects = {{ result[1] }}</h2> 

</body>
</html>

1 个答案:

答案 0 :(得分:0)

Ajax调用是由浏览器发起的异步请求,当它收到服务器响应时,不重新加载页面

IMO,由于要渲染模板,因此不应使用AJAX,而应使用常规的<form>元素或以编程方式创建表单,填充数据,然后使用jQuery('selector').submit()提交。

相关问题