gpt4 book ai didi

javascript - 在 Python/Flask 中访问 HTML 表单数据

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:49 27 4
gpt4 key购买 nike

我正在与一个合作伙伴合作开发一个使用 Flask 的项目,该项目需要将一个(变量)JSON 对象从 HTML 文件传递​​到 app.py 文件,从而查询我们的数据库。我的合作伙伴使用文本输入字段成功地编写了一个版本,将检索到的记录打印到控制台。然而,我们在实现下拉菜单时已经做了很多改变,但我们无法让事情再次正常工作。

就目前而言,我能够 ping app.py 文件并返回一个虚拟响应(例如,在控制台上打印“hello”),但我似乎无法访问通过以下方式传入的实际数据JSON 对象。 (我什至还没有搞乱数据库——只是试图操作该对象。)最近,我收到了 GET (url) 500(内部服务器错误),当我使用 POST 方法时也是如此。

我读过很多类似问题的讨论(仅举几例 hereherehere ),并尝试了几种不同的方法。我想我一定是在表单上做错了什么,而且解决方案似乎应该相当简单,但我没有太多运气来解决它。

以下是相关的 HTML 和 Javscript:

<!-- establish the Flask form which will send the selected airports to the Python code and database -->
<form name="selected_route" id="selected_route" method="GET">

<p>Departure</p>
<p>
<!-- dropdown menu for departure state -->
<select name="departure_state" id="departure_state" onChange="changeDepAirport(this.value);">
</select>

<!-- dropdown menu for departure airport, generated by choice of state -->
<select name="departure_airport" id="departure_airport">
<option value="" disabled selected>Select an airport</option>
</select>
</p>

<p>Arrival</p>
<p>
<!-- dropdown menu for arrival state -->
<select name="arrival_state" id="arrival_state" onChange="changeArrivAirport(this.value);">
</select>

<!-- dropdown menu for arrival airport, generated by choice of state -->
<select name="arrival_airport" id="arrival_airport">
<option value="" disabled selected>Select an airport</option>
</select>
</p>

<!-- submit button for the departure and arrival parameters, which will visualize the data for that route -->
<p>
<button name="go" id="go" type="submit" onclick="retrieveRouteData()">Go!</button>
</p>
</form>

<script>
// function to retrieve the data for the selected route
function retrieveRouteData() {
departure_airport = document.getElementById("departure_airport").value;
arrival_airport = document.getElementById("arrival_airport").value;
route_object = { "departure_airport" : departure_airport,
"arrival_airport" : arrival_airport};
console.log(route_object);

testAj(function(output){
console.log("1")
console.log(output)
});

function testAj(handleData) {
$(document).ready(function() {
$('form').submit(function (e) {
var url = "{{ url_for('test') }}"; // send the data here
$.ajax({
type: "GET",
url: url,
data: route_object,
success: function (data) {
console.log(data) // display the returned data in the console.
}
});
e.preventDefault(); // block the traditional submission of the form.
});
});
};
};

generateStateLists(); // calls the function to populate the initial dropdowns

</script>

这是 Python 代码:

from flask import Flask, jsonify, render_template, redirect, url_for, g, Response, request
from flask_cors import CORS
from flask_wtf import FlaskForm
from wtforms import StringField
from pymongo import MongoClient
from bson import json_util
from bson.json_util import dumps
import json
import os

app = Flask(__name__)
app.secret_key = ####

@app.route('/')
def home():
print("come to home")
return render_template('home.html')

# send json file
@app.route('/send')
def send():
return "<a href=%s>file</a>" % url_for('static', filename='StateCityCode.json')


@app.route('/test', methods=['GET'])
def test():
data = request.get_json()
return data

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

提前感谢您的帮助!

最佳答案

在发送之前尝试对 json 数据进行字符串化,并显式设置调用的 json header ,如下所示:

$.ajax({
type: "POST",
dataType: "json",
url: url,
data: JSON.stringify(route_object),
contentType: "application/json;charset=utf-8"
success: function (data) {
console.log(data) // display the returned data in the console.
}
});

关于javascript - 在 Python/Flask 中访问 HTML 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com