如何使用 JQuery Ajax 和 Flask 创建请求和响应

How can I create a request and response with JQuery Ajax and Flask

所以我是 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%;
}

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

删除 app.run() 中的“主机”参数并将 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”记录到浏览器控制台