php - 我如何使用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;
?>
推荐阅读
- loops - 序言,无限循环
- node.js - 如何根据数组中的值在 dynamoDB 中进行扫描?
- laravel - Laravel orderBy created_at 和另一个时间字段
- node.js - 在 OpenCV calibrateCamera cameraMatrix 和 distCoeffs 参数中使用什么作为输入?
- python - 何时使用 tensorflow 的内部 API(例如 tf.python.ops.*)?
- angular - 使用不同的模板登录 - Angular 6
- google-bigquery - 在 Google Big_Query 中显示当月的第一天
- php - Laravel 505 错误
- r - 创建包时如何使R找到依赖项的本地包
- powershell - PowerShell 搜索字符串和复制文件