如何从javascript发送多个无线电组值

时间:2016-02-27 06:12:44

标签: javascript php jquery ajax

这是一个添加到购物车系统。现在我可以发送带有id的数量。但我想发送无线电组的价值也..这是怎么做的 这是我的代码

product.php

<script>
jQuery(function ($) {

$('.popbutton').on('click', function () {
    var id = $(this).data('id');
    var qtyValue = $("input[type='text'][name='qty']").val();
    var radio = $("input[type='radio'][name='answer[]']").val();
    $.ajax({
        url: 'ajax.php',
        data: {
            id: id,
            quantityValue : qtyValue, 
            radioValue : radio
        },
        method: 'POST',
        success: function (html) {
            $('body').append(html);
            $(html).bPopup();
        },
        error: function (returnValue) {}
    });
});


});
</script>

我在product.php中的广播组

Capacity:
<label><input type="radio" name="answer[1]" value="8"> 8 GB </label><br />
<label><input type="radio" name="answer[1]" value="4"> 4 GB </label><br />
Type:
<label><input type="radio" name="answer[2]" value="sony"> Sony </label><br />
<label><input type="radio" name="answer[2]" value="samsung"> Samsung </label>

<input id="qty" type="text" class="w30" name="qty" size="2" value="1" /><br />

<button id="button-cart" class="popbutton" data-id="40">Add to Cart</button>

ajax.php

$answers = $_POST['radioValue'];

foreach ($answers as $answer) {
    echo $answer;
//not work
}

2 个答案:

答案 0 :(得分:3)

*var datastring = $("#contactForm").serialize();
        $.ajax({
            type: "POST",
            url: "your url.php",
            data: datastring,
            dataType: "json",
            success: function (data) {
                // do what ever you want with the server response
            },
            error: function () {
                alert('error handing here');
            }
        });*

答案 1 :(得分:1)

将所有需要的输入包含在表单

    <form id="yourForm" onsubmit="return false;">
        Capacity:
        <label><input type="radio" name="answer[1]" value="8"> 8 GB </label><br />
        <label><input type="radio" name="answer[1]" value="4"> 4 GB </label><br />
        Type:
        <label><input type="radio" name="answer[2]" value="sony"> Sony </label><br />
        <label><input type="radio" name="answer[2]" value="samsung"> Samsung </label>

        <input id="qty" type="text" class="w30" name="qty" size="2" value="1" /><br />

        <button id="button-cart" class="popbutton" data-id="40">Add to Cart</button>
    </form>

然后你的javascript

    $('.popbutton').on('click', function () {
        var data = $('#yourForm').serialize();
        $.ajax({
            url: 'ajax.php',
            data: data,
            method: 'POST',
            success: function (html) {
                $('body').append(html);
                $(html).bPopup();
            },
            error: function (returnValue) {}
        });
    });

您可以通过

访问ajax.php上的无线电值
    print_r($_POST['answer']);