我刚刚使用ajax在多个复选框上完成了小项目。可以在此处找到演示:demo。但现在我想使用提交按钮进行过滤选项。因此,现在选择了多个复选框并点击了sumbit按钮后,只有它应该在手机数据库中更改。有帮助吗?谢谢。这是我的代码: 的index.php
<body>
<h1>Phones database</h1>
<table id="phones">
<thead>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Model</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="filter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="Samsung" checked>
<label for="Samsung">Samsung</label>
</div>
<div>
<input type="checkbox" id="iPhone" checked>
<label for="iPhone">iPhone</label>
</div>
<div>
<input type="checkbox" id="HTC" checked>
<label for="HTC">HTC</label>
</div>
<div>
<input type="checkbox" id="LG" checked>
<label for="LG">LG</label>
</div>
<div>
<input type="checkbox" id="Nokia" checked>
<label for="Nokia">Nokia</label>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
console.log(data);
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getPhoneFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updatePhones(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#phones tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getPhoneFilterOptions();
updatePhones(opts);
});
$checkboxes.trigger("change");
</script>
</body>
</html>
submit.php
<?php
require 'Database.php';
#### TEMP SET NAMES FÜR UTF8 ###################################################
include 'Json.php';
$opts = $_POST['filterOpts'];
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query =
'SELECT mobile_phone.id, name, model, price FROM mobile_phone INNER JOIN brand ON brand_id = brand.id WHERE name IN ('.implode(",", $tmp).')';
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
答案 0 :(得分:0)
此行data: {filterOpts: opts},
更改为
data: {filterOpts: $(':checked').val('id')}
这应该传递模型的ID。