【问题标题】:Send multiple checkbox data with ajax使用ajax发送多个复选框数据
【发布时间】:2017-11-15 11:38:01
【问题描述】:

我有一个表格,其中有要插入数据库的复选框格式的国家/地区列表。比如说:

<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>

我想使用 ajax 将其插入数据库。我可以通过普通的同一页面 PHP 帖子轻松完成此操作。但是当使用 ajax 将数据发送到其他页面进行处理时,我对如何发送感到困惑。一旦它完美地发送了所有选定的复选框值,那么剩下的就交给我了。

我的 AJAX 脚本

$("#submit").click(function() {
    var dataString = {
    clicks: $("#clicks option:selected").data("value"),
    country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work. 
    };
$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to purchase this advertisement?',
    buttons: {
    confirm: function () {
                $.ajax({
                    type: "POST",
                    dataType : "json",
                    url: "add-ptc-process.php",
                    data: dataString,
                    cache: true,
              beforeSend: function(){
                    $("#submit").hide();
                $("#loading-rent").show();
                        $(".message").hide();
              },
                    success: function(json){
                setTimeout(function(){
                        $(".message").html(json.status).fadeIn();
                    $('#mywallet').html('$' + json.deduct);
                  $("#loading-rent").hide();
                  $("#submit").show();
                    },1000);
                    }
                });
    },
    cancel: function () {
      $.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
    }
    }
    });
    return false;
});
});

我已经在处理页面上进行了检查,如果国家/地区值为空,则返回错误,例如:

if($country == ''){
    echo "No countries selected. Please select at least one country.";
}

无论我选择一个或所有国家/地区,我仍然会收到此错误响应。我应该怎么做才能用 ajax 发送这些复选框数据?

【问题讨论】:

  • 您可能需要使用$("input[name=country").val() 而不是$("input[name=country").data("value")。 .data() 假设有一个 data 属性,在这种情况下 data-value="something" 你没有。您可能只想.serialize() 表单,这样更直接。
  • 不能使用普通表单提交的原因是什么?你尝试的方式行不通,因为name='country[]' != name='country'
  • @Lixus 也说了我要说的,你可能需要发"input[name=country\\[\\]]"
  • 我在这个链接stackoverflow.com/questions/9493531/… 上得到了 sbczk 的一个答案,我想这会起作用.. 看起来是这样.. 但是如何在我的代码中实现它给了我一个问题,因为我不是ajax 太好了... somone 可以查看这个答案并帮助我在我的 ajax 代码中实现它吗?
  • 该答案假定您的表单中没有其他复选框,否则它将包含在 country[] 复选框中。如果这些是唯一的复选框,那么该答案将正常工作。

标签: javascript php jquery ajax checkbox


【解决方案1】:

您需要在输入捕获上将.data() 切换为.val()。还将输入的名称更改为input[name=country\\[\\]]:checked。

# Use "e" as the event
$("#submit").click(function(e) {
    # Use this function to stop the form
    e.preventDefault();
    # You could make a quick function to save all the countries
    # You can actually feed other selectors into this as well, so
    # it can do all your value retrievals, not just for countries
    function getCountries(checkboxes)
        {
            var getVals =   [];
            $.each($(checkboxes),function(k,v) {
                getVals.push($(v).val());
            });

            return getVals; 
        }

    var dataString = {
        clicks: $("#clicks option:selected").val(),
        # Run the function to gather
        # Note the name (escaped [] with :checked)
        country: getCountries("input[name=country\\[\\]]:checked")
    };

    $.confirm({
        title: 'Confirm!',
        content: 'Are you sure you want to purchase this advertisement?',
        buttons: {
            confirm: function () {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "add-ptc-process.php",
                    data: dataString,
                    cache: true,
                    beforeSend: function(){
                        $("#submit").hide();
                        $("#loading-rent").show();
                        $(".message").hide();
                    },
                    success: function(json){
                        setTimeout(function(){
                            $(".message").html(json.status).fadeIn();
                            $('#mywallet').html('$' + json.deduct);
                            $("#loading-rent").hide();
                            $("#submit").show();
                        },1000);
                    }
                });
            },
            cancel: function () {
                $.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
            }
        }
    });
});

【讨论】:

    【解决方案2】:

    试试

    var countries = {};
    $('input[name^="country"]').each(function(){
              countries[$(this).attr('value')] = $(this).is(":checked");
    });
    

    然后将其发布到 ajax 数据:国家或更改代码以仅发送选中的元素

    您的 PHP 将收到一个数组,以便您检查

    if(is_array($_POST['countries'])){
             foreach($_POST['countries'] AS $country_name => $is_checked){
                      //do something...
             }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2015-10-11
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      相关资源
      最近更新 更多