繁体   English   中英

我如何使用ajax php过滤复选框

[英]How can i filter on checkbox using ajax php

我在 codeigniter 中使用 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脚本

test.php 示例只返回选定的复选框值

<?php 

echo ($_REQUEST['id']);
exit;

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM