如何通过ajax将多个单选按钮值发送到php


how to send multiple radio button values via ajax to php

我有多个按名称区分的单选按钮,这是我的脚本

<?php
            if(mysqli_num_rows($result)>0){
                while($row = $result->fetch_assoc()){ ?>
                    <tr>
                        <td><?php echo $row['fullname'];?></td>
                        <td><?php echo $row['email'];?></td>
                        <td><?php echo $row['class'];?></td>
                        <td><input type="radio" value="present" name="<?php echo($row['id']); ?>" checked></td>
                        <td><input type="radio" value="absent" name="<?php echo($row['id']); ?>"></td>
                    </tr>
                <?php }
            }
            ?>

我想把它们的值传递给php脚本,我如何传递每个单选组的值,假设mysql查询返回了10行,那么就有10个单选按钮组,我需要发送所有单选按钮的值。我的ajax调用是

$("#submitAttendance").click(function(){
                $.ajax({
                    url: 'teacher.php',
                    method: 'post',
                    data:
                });
            }); 

您可以使用$(form_selector).serialize()来序列化表单的所有值,并将其作为预期输入发送到服务器。

$("#submitAttendance").click(function(){
    $.ajax({
        url: 'teacher.php',
        method: 'post',
        data: $(form_selector).serialize()
    });
});

此外,请确保您将此代码写入:

$(form_selector).submit()

而不是将事件处理程序附加到提交按钮。

所以,你的表单的一个典型输出,比如这样说:

<form action="">
  <div>
    <label><input type="radio" name="student-1" id="" value="present"> Present</label>
    <label><input type="radio" name="student-1" id="" value="absent"> Absent</label>
  </div>
  <div>
    <label><input type="radio" name="student-2" id="" value="present"> Present</label>
    <label><input type="radio" name="student-2" id="" value="absent"> Absent</label>
  </div>
  <div>
    <label><input type="radio" name="student-3" id="" value="present"> Present</label>
    <label><input type="radio" name="student-3" id="" value="absent"> Absent</label>
  </div>
  <div>
    <label><input type="radio" name="student-4" id="" value="present"> Present</label>
    <label><input type="radio" name="student-4" id="" value="absent"> Absent</label>
  </div>
  <div>
    <label><input type="radio" name="student-5" id="" value="present"> Present</label>
    <label><input type="radio" name="student-5" id="" value="absent"> Absent</label>
  </div>
</form>

将是:

"student-1=absent&student-2=present&student-3=absent&student-4=present&student-5=absent"

这就是你要找的吗?你可以使用PHP使用

$_POST["student-1"]  // absent
$_POST["student-2"]  // present
$_POST["student-3"]  // absent
$_POST["student-4"]  // present
$_POST["student-5"]  // absent