flask form ajax post,javascript - AJAX Post Request to Python Flask - Stack Overflow

This question already has answers here:

Closed 3 years ago.

Trying to understand how to send post requests to my backend (flask).

In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.

$(document).ready(function() {

$("#loadData").click(getChecked);

});

function getChecked() {

event.preventDefault();

var checkboxes = $(".form-check input[type=checkbox]:checked");

//toArray: convert checkboxes object to javascript array

var labels = checkboxes.toArray().map(checkbox => checkbox.value);

$.ajax({

url: 'api/regions',

type: "POST",

data: JSON.stringify(labels),

processData: false,

contentType: "application/json; charset=UTF-8",

success: function(response) {

console.log(response);

},

error: function(error) {

console.log(error);

}

});

}

In my app.py I have a route for my endpoint api:

@app.route('/api/regions', methods=['POST'])

def regions():

regions = request.json

with open("C:\\test.txt", 'w') as f:

f.write(regions)

if __name__ == "__main__":

app.run(debug=True)

I understand there is no return statement, I'm just trying to write the data I get from

regions = request.json

to a file. "C:\test.txt"

The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值