【问题标题】:render_template does nothing after receiving ajax content (flask, python, javascript)render_template 在接收到 ajax 内容(flask、python、javascript)后什么都不做
【发布时间】:2020-12-08 06:11:39
【问题描述】:

当满足条件时,我正在使用 ajax 将数据传递给我的 python 函数:

        if (lesson.length === 0) {
            $.ajax(
                {
                    type:'POST',
                    contentType:'application/json',
                    dataType:'json',
                    url:'http://127.0.0.1:5000/result?value=' + errors ,
                    success:function(response){ document.write(response); }  
                }
            );
        }

我知道信息被正确接收,因为我可以通过打印在终端中看到它:

127.0.0.1 - - [19/Aug/2020 11:59:46] "GET /static/flexjava.js HTTP/1.1" 200 -
0
127.0.0.1 - - [19/Aug/2020 11:59:48] "POST /result?value=0 HTTP/1.1" 200 -

但是 python 在 print() 函数之后什么都不做。渲染或重定向都不起作用,即使信息传递,浏览器也会保持原样:

@app.route("/result", methods=["GET", "POST"])
def result():
    content = request.args.get('value')
    if "username" not in session or session["username"] == "guest":
        return redirect("/login")
    if request.method == "GET":
        return redirect("/")
    else:
        print(content)
        return render_template("finished.html")

【问题讨论】:

    标签: javascript python ajax web flask


    【解决方案1】:

    您没有正确使用 ajax。您希望收到 json 回复,而不是完整的网页。

    试试:

    $.ajax(
            {
                type:'POST',
                contentType:'application/json',
                dataType:'json',
                url:'http://127.0.0.1:5000/result?value=' + errors ,
                success:function(response){ 
                    console.log(response);
                    document.write(response); # not a good idea
                    # I would use something like:
                    # document.getElementById("myDiv").innerText = response.content;
                }  
            }
        );
        
    

    然后:

    from flask import jsonify
    
    @app.route("/result", methods=["GET", "POST"])
    def result():
        content = request.args.get('value')
        ...
        else:
            print(content)
            return jsonify(
                {
                    "content": content
                }
            )
    

    这个功能真的什么都不做,因为你已经在调用模板中有errors。如果你想去finished,你可以在ajaxsuccess回调中这样做:

    success:function(response){ 
        console.log(response);
        window.location.replace(window.location.href + "finished");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多