【发布时间】:2014-07-14 23:10:57
【问题描述】:
我刚刚使用 ajax 完成了多个复选框的小项目。但现在我想使用提交按钮进行过滤选项。因此,现在在选择多个复选框并单击 sumbit 按钮后,只有它应该在电话数据库中更改。有什么帮助吗?谢谢。 这是我的代码: 索引.php
<script>
function makeTable(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "",
currRecord = this;
$.each(this, function(k , v) {
if(k==='model'){
v = "<a href='content.php?id=" + currRecord['id'] +"'>" + v + "</a>";
} else if (k==='price'){
v = "<span class='price'>" + v + "</span>";
}
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){
if(!opts || !opts.length){
opts = allBrands;
}
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#phones tbody').html(makeTable(records));
updatePrices();
}
});
}
function subsidyIsValid(){
var amount1 = $("#amount1").val(),
amount2 = $("#amount2").val(),
regex = /^\d+$/,
inputValid = false;
if(regex.test(amount1) && regex.test(amount2)){
var newTotal = Number(amount1) + Number(amount2)
$("#total").text(newTotal);
inputValid = true;
}
return inputValid
}
function updatePrices(){
var subsidyTotal = Number($("#total").text());
$(".price").each(function(){
var origVal = Number($(this).text())
$(this).text(origVal - subsidyTotal)
})
}
$("#submitFilter").on("click", function(){
var opts = getPhoneFilterOptions();
updatePhones(opts);
})
$("#apply").on("click", function(){
if(subsidyIsValid()){
$(this).prop("disabled", true);
$(this).next().prop("disabled", false);
updatePrices();
} else {
alert("Subsidy invalid!")
}
});
$("#remove").on("click", function(){
$("#amount1").val("");
$("#amount2").val("");
$("#total").text("0");
$(this).prop("disabled", true);
$(this).prev().prop("disabled", false);
$checkboxes.trigger("change");
});
var allBrands = [];
$("input[type=checkbox]").each(function(){
allBrands.push($(this)[0].id)
})
updatePhones();
updatePrices();
</script>
提交.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);
?>
【问题讨论】:
-
所以它应该只在点击提交后过滤结果?
-
是的,只有在提交后它才应该更新数据库。我已经创建了提交按钮并尝试在 onclick 上调用函数 updatePhones(opts) 但它不起作用..
标签: javascript php ajax checkbox