我当前的代码从表单获取所有数据,然后将其作为数组输出到控制台(我正在测试联系表单)。它返回的所有数据都是正确的,但单选按钮的值始终相同。

的HTML:

<form class="form1" action="form.php" method="post">
<div class="form-sect">
    <div class="formb-check">
        <input type="text" name="name" placeholder="Name" class="formb-small">
        <input type="text" name="id" placeholder="ID: 00000000" class="formb-small">
    </div>
</div>
<div class="form-sect">
    <div class="formb-srv">
        <div class="formb-check">
            <input type="radio" name="server" id="server-1" value="Srv 1"><label for="server-1">Server 1</label>
            <input type="radio" name="server" id="server-2" value="Srv 2"><label for="server-2">Server 2</label>
        </div>
    </div>
</div>
<div>
    <div>
        <textarea name="message" placeholder="Message....."></textarea>
        <button type="submit" name="submit">Submit Report</button>
    </div>
</div>




jQuery的:

$('form.form1').on('submit', function() {
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

    data[name] = value;
});

$.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response){
        console.log(response);
    }
});

return false; });


PHP:

<?php
if(isset($_POST['name'], $_POST['id'], $_POST['server'], $_POST['message'])){
    print_r($_POST);
} ?>


在我用来测试单选按钮的值的数组中,总是使用的第二个值,在此代码中为Srv2。如下所示:
[服务器] => Srv 2

最佳答案

您应该像这样序列化表格:

$('form.form1').on('submit', function(event) {
    event.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function (response) {
            console.log(response);
        }
    });
});

07-28 11:13