html复选框怎么向后端传值,前端获取checkbox复选框的值 通过数组形式传递

本文介绍如何在HTML中获取复选框的值,并通过JavaScript将选中的值以数组形式通过Ajax传递到Python后端。后端通过请求接收数据,处理并保存。主要涉及前端jQuery操作、Ajax提交及Python的Flask框架处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html代码:

应用一组

{% for peopel_1 in peopels_1 %}

{{ peopel_1.name }}

{% endfor %}

应用二组

{% for peopel_2 in peopels_2 %}

{{ peopel_2.name }}

{% endfor %}

提交

js代码:

1 获取已选中的名字并放到数组中

var name_list = [];

$("input[name='people_name']:checked").each(function(){

name_list.push($(this).val)

});

2 利用ajax向后台传递form表单数据

$(".select_people").submit(function(event){

event.preventDefault();  // 阻止默认表单的action功能

var name_list = [];

$("input[name='people_name']:checked").each(function(){

name_list.push($(this).val)

});

data = {'id': 1, 'names': name_list};

$.ajax({

url: "task_mgm/********",

type: "POST",

data: JSON.stringify(data),

contentType: "application/json",  //发送到后台的数据格式

data_type: "json",  // 接收后端返回的数据格式

success: function(resp){

if (resp.error == "OK"){ console.log('分享成功') }

else { console.log('分享失败') }

}

});

})

python后台代码:

071b9c07855ff108dbf93e9ebb883df3.png

ef0b22e376e38997e907b437a93e4cfe.png

1 @task_mgm.route('/taskinfo_share_people', methods=['POST', 'GET'])2 @login_required3 deftaskinfo_share_people_fun():4 datas =request.get_json()5 task_id = datas.get('id')6 sharePeopleList = datas.get('names')7 print(sharePeopleList)8 task =ShareTask()9 if len(sharePeopleList) >0:10 task.taskId =task_id11

12 sharePeopleList = list(set(sharePeopleList)) #去重

13 sharePs = ','.join(sharePeopleList)14 task.sharePeopleTo =sharePs15 task.sharePeopleFrom =current_user.name16 db.session.add(task)17 db.session.commit()18 return jsonify(error='OK', emsg="True")19 else:20 return jsonify(error='NO', emsg="False")

View Code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值