【问题标题】:How can I create a request and response with JQuery Ajax and Flask如何使用 JQuery Ajax 和 Flask 创建请求和响应
【发布时间】:2026-02-20 09:35:02
【问题描述】:

所以我是 JQuery 和使用 Flask 的新手,我一直在尝试弄清楚如何将数据发送到我的服务器,然后成功发送回响应,但是,我尝试和阅读的所有内容都没有好像不行。

就我想要做的而言,我有一个带有一些复选框输入的简单 html 表单。我想将提交时的表单数据发送到服务器,这样我就可以对其进行管理,然后发回响应。我现在对管理它并不太在意,我只是想弄清楚为什么它们之间的连接不起作用。我没有记录任何错误,但似乎没有任何反应(因此假设我的 JS 或 Python 编写不正确)。我目前在我的 Python 代码中有一个打印行,以查看它是否达到了该点,但似乎没有。

我想知道是否有什么具体的我做错了阻止请求按预期工作?

这是我的 JS 文件中的当前尝试:

$(document).ready(function(){

    $("#filterform").on("submit", function(e){
        e.preventDefault();

        var datastring = $(this).serialize(); 
        $.ajax({ 
            type: "GET",
            url: "/movies",
            data: datastring,
            dataType: "json", 

            success: function(response_data){
                console.log(response_data);
            },
            error: function() {
                console.log("request failed");
            }
        })
    });
});

跟进,这是我的 app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/movies", methods = ["GET"])
def movies():
    print("test")
    return request.args()

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0")

我的 HTML 和 CSS 的简化版本,供任何想要复制它的人使用:

<!DOCTYPE html>
<head>
    <title>Movie Selection</title>
    <link rel="stylesheet" href="../static/main_styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="scripts/main.js"></script>
</head>
<body>
    <div id="palette">
        <div class="palette_item" id="palette_item">BOX1</div>
        <div class="palette_item">BOX2</div>
        <div class="palette_item">BOX3</div>
        <div class="palette_item">BOX4</div>
    </div>
    <div id="detailrow">
        <form id="filterform" method="get">
            <div id="filtersrow">
                <div>
                    Action <input type="checkbox" class="filter" name="action">
                </div>
                <div>
                    Family <input type="checkbox" class="filter" name="family">
                </div>  
            </div>
            <div id="buttonrow">
                <input type="submit" value="Generate" id="submitbtn">
            </div>
        </form>
    </div>
</body>
</html>
#palette {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
    box-sizing: border-box;

    background-color: rgb(52, 148, 148);
}

.palette_item {
    flex-direction: column;
    flex-wrap: wrap;

    width:20%;

    text-align: center;
    background-color: white;
    border: 2px solid black;
}

#detailrow {
    display:flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}

#filtersrow {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    padding-top:5%;
}

#buttonrow {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;

    padding-top: 5%;
}

【问题讨论】:

    标签: python jquery ajax flask python-requests


    【解决方案1】:

    您不能使用/movies 作为请求的 URL,只要您不将请求代理到您的服务器。

    删除app.run()中的“host”参数,并将ajax请求发送到http://127.0.0.1:5000/movies而不是/movies

    这应该可以解决问题。

    编辑:

    所以有两件事是你想要改变的。 首先在js文件中

    $(document).ready(function(){
    
        $("#filterform").on("submit", function(e){
            e.preventDefault();
    
            var datastring = $(this).serialize(); 
            console.log(datastring)
            $.ajax({ 
                type: "GET",
                url: "http://127.0.0.1:5000/movies", // change the url to localhost
                data: datastring,
                dataType: "json",  // if you use json here, the response should be json too, otherwise jquery will try to convert 
                                   // the response to json and throw an error if it fails
    
                success: function(response_data){
                    console.log(response_data);
                },
                error : function(request,error)
                {
                alert("request failed");
                }
            })
        });
    });
    

    在 .py 文件中

    from flask import Flask, render_template, request
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app) # add cors so you don't get a cors error
    
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    
    @app.route("/movies", methods=["GET"])
    def movies():
        print("test")
        return {"message": "Hello World"} #you have to return json here as explained in the js file
    
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    它应该将“Hello World”记录到浏览器控制台

    【讨论】:

    • 嗨@Rubikalubi,感谢您的建议。不幸的是,我之前已经尝试过这种方法,但没有奏效。
    • @Kiana,你能提供完整的源代码,以便我在我的机器上测试它吗?
    • 我刚刚编辑了帖子以包含我的 html 和 css,因为仅此而已 - 希望这会有所帮助。
    • @Kiana 好的,我调查了一下,ajax 请求还有一个错误,我现在上传正确的代码