簡體   English   中英

如何通過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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM