如何使用 JQuery Ajax 和 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()中的"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"记录到浏览器控制台

最新更新