我有一个php页面,其中有一个ajax连接select和一个div,其中包含表tb1中的记录总数
HTML
<p>
<select name="model" id="model">
<?php echo $myclass->selModel(); ?>
</select>
</p>
<br />
<p>
<select name="year" id="year">
<option value=""> </option>
</select>
</p>
<p>
<div id="total"><?php echo $myclass->recordNum();?></div>
</p>
JS
// VARS
var wait = '<option>Waiting</option>';
var select = '<option value="">Select</option>';
// CAT_1 //
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
switch (data) {
case select:
$("select#year").html("");
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(data);
return false;
}
});
});
PHP - select-concat.php
if(isset($_POST['model']))
{
echo $myclass->selYear();
die;
}
MY PHP CLASS
public function selYear() {
$result = $this->db->mysqli->query
("SELECT year FROM tb1 WHERE model='$_POST[model]");
$year = '<option value="">Select</option>';
while($row = $result->fetch_assoc()) {
$year .= '<option value="' . $row['year'] . '"';
$year .= '>' . $row['year'] . '</option>';
}
return $year;
}
private function recordNum(){
$result = $this->db->mysqli->query
("SELECT * FROM tb1 WHERE something ");
$numrec = $result->num_rows;
return $numrec;
}
我的目标是每次运行连接选择时用ajax更新记录数。我怎么能这样做?感谢
答案 0 :(得分:1)
你应该在select-concat.php上使用json_encode()来返回两个结果。
if(isset($_POST['model']))
{
$years = $myclass->selYear();
$total = $myclass->recordNum();
$arr = array('years' => $years, 'total' => $total);
echo json_encode($arr);
die;
}
您必须将POST模型值添加到recordNum()
函数(或使用参数传递)。
则...
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
var json_data = $.parseJSON(data);
switch (data) {
case select:
$("select#year").html("");
$("#total").html(0);
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(json_data.years);
$("#total").html(json_data.total);
return false;
}
});
});