如何使用 ajax php 过滤复选框



我在代码点火器中使用ajax,我现在有不同的复选框,每当有人检查时我都想要复选框,结果应该根据用户选择的复选框来,那么我该怎么做呢?这是我的代码

<input type="checkbox" class="styled" id="Baker" value="Bakers">
<label for="role1">Bakers</label>
<input type="checkbox" class="styled" id="Bakerd" value="Bakersd">
<label for="role1">Bakersd</label>
<script>
    $('.styled').click(function() {
    alert($(this).attr('id'));  
       if(this.checked){
            $.ajax({
                type: "POST",
                url: 'searchOnType.php',
                data: $(this).attr('id'), 
                success: function(data) {
                    alert('it worked');
                    alert(data);
                    $('#container').html(data);
                },
                 error: function() {
                    alert('it broke');
                },
                complete: function() {
                    alert('it completed');
                }
            });
            }
      });
</script>   

html

<ul class="unstyled centered">
    <li>
        <input type="checkbox" class="styled-checkbox" id="Baker" value="" onchange="checkBoxOnChange(this);">
      <label for="role1">Baker</label>
    </li>
    <li>
      <input type="checkbox" class="styled-checkbox" id="Barista" value="" onchange="checkBoxOnChange(this);">
      <label for="role2">Barista</label>
    </li>
    <li>
      <input type="checkbox" class="styled-checkbox" id="Bartender" value="" onchange="checkBoxOnChange(this);">
      <label for="role3">Bartender</label>
    </li>
    <li id="filter">
    </li>
  </ul>

jQuery 脚本

<script>
        function checkBoxOnChange(isChecked){
            if($(isChecked).is(":checked")){
                console.log("check");
                $.ajax({
                url: 'test.php',
                type: 'POST',
                data: {id: $(isChecked).attr('id')}, // I suggest you to use $(isChecked).val(). Add value in html same as id
                success: function(data){
                    console.log(data);
                    $("#filter").text(data);
                }
                }
              );
            }else{
                console.log("Uncheck");
            }
        }
        </script>

php 脚本

测试.php示例仅返回选定的复选框值

<?php 
echo ($_REQUEST['id']);
exit;
?>

最新更新