Ajax连接选择和总记录查询


Ajax concatenate select and total record query

我有一个php页面,其中有一个ajax连接选择和一个div,其中包含表tb1 中的记录总数

HTML

<p>
<select name="model" id="model">
        <?php echo $myclass->selModel(); ?>
</select>
</p>
<br />
<p>
<select name="year" id="year">
    <option value="">&nbsp;</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;
}

我的PHP类

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;
}

我的目标是每次运行concatenate select时都用ajax更新记录的数量。我怎么能那样做?感谢

您应该在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;
        }
    });
});