如何通过Ajax将选中radio的value与data-id属性提交给PHP后端
实现方法
你只需要在遍历选中单选框时自行组装需要提交的数据结构,再传入$.ajax的data参数即可,不需要依赖serialize方法。
示例代码(按数组格式提交,适合后端批量接收答题记录)
$("form").submit(function(event){ // 阻止默认表单提交 event.preventDefault(); // 初始化提交数据容器 const answerList = []; // 遍历所有选中的单选框 $('.answer:checked').each(function() { const $item = $(this); answerList.push({ question_key: $item.attr('name'), // 对应题目字段名q1/q2 answer_value: $item.val(), // 选项值 answer_data_id: $item.data('id') // 自定义data-id属性 }); }); // 发送请求 $.ajax({ url: "你的后端接收接口地址", method: "POST", // 如果后端要求接收JSON格式数据,保留下面两行 contentType: "application/json;charset=utf-8", data: JSON.stringify(answerList), // 如果后端接收普通表单格式,把上面两行替换为 data: answerList 即可 success: function (response) { // 提交成功后的处理逻辑 }, error: function (error) { // 提交失败的处理逻辑 } }); });
按题目名为键的对象格式提交(适合后端按字段接收)
$("form").submit(function(event){ event.preventDefault(); const submitData = {}; $('.answer:checked').each(function() { const $item = $(this); submitData[$item.attr('name')] = { value: $item.val(), data_id: $item.data('id') }; }); $.ajax({ url: "你的后端接收接口地址", method: "POST", data: submitData, success: function (response) { // 提交成功逻辑 } }); });
两种方式都会自动过滤未选中的单选框,仅提交有选中值的题目数据,完全符合需求。
内容的提问来源于stack exchange,提问作者user_m
相关产品推荐
相关产品推荐

