用AJAX发送表单和其他数据到flask端点



我试图通过AJAX向Flask端点发送两个数据-一个表单和一个数组。我的javascript只发送表单在这里:

$(document).on('click', '#submit_button', function(){
let form_data = $('#form').serialize();
let other_data = updateOtherData();
req  = $.ajax({
url : url_final,
type : 'POST',
data : form_data
});
req.done(function(data){
//does some updates to page here
});
});

在我的flask端点中,这样做很好:

@app.route('/process_form', methods=['GET', 'POST'])
def process_form():
form = MyForm()
if request.method == 'POST' and form.validate_on_submit():
#do something here
return some_data_back

但是,我想将other_dataform_data一起发送。所以我试过:

$(document).on('click', '#submit_button', function(){
let form_data = $('#form').serialize();
let other_data = updateOtherData();
req  = $.ajax({
url : url_final,
type : 'POST',
data : {'form': form_data, 'other': JSON.stringify(other_data)}
});
req.done(function(data){
//does some updates to page here
});
});

并将我的端点更新为:

@app.route('/process_form', methods=['GET', 'POST'])
def process_form():
form = MyForm()
if request.method == 'POST':
form = #Turn this back to a FlaskForm object
other_data = #Just get this as a string
if request.method == 'POST' and form.validate_on_submit():
#do something here
return some_data_back

我在上面尝试了很多不同的部分,我不能让它工作。我已经试过了。形式,请求。数据和请求。get_json(我在ajax调用中设置了contentType)。

我看过很多类似的问题,比如:获取在Flask请求中接收到的数据和在Python Flask中获取原始POST主体,不管Content-Type头看起来很有希望,但所有内容都是空的。

你可以直接使用'request.json'

@app.route('/process_form', methods=['GET', 'POST'])
def process_form():
form = MyForm()
if request.method == 'POST':
content = request.json 
form = content['form']
other_data = content['other']
if request.method == 'POST' and form.validate_on_submit():
#do something here
return some_data_back

最新更新