通过jQuery提交后自动填充选择

时间:2015-04-27 10:45:13

标签: php jquery ajax

我有一个用户可以选择汽车品牌的表单。之后,我发送一个带有Ajax的SQL查询,用所选品牌的所有模型填充下一个选择。 当表单被提交时,我通过PHP检查它,如果有任何错误,我将返回上一个表单,并显示错误消息并填写字段。

问题在于'模型'字段有"触发"树立品牌变革。 我该如何解决这个问题:再次调用jquery(在select中显示模型)并将之前的模型显示为选中?

Ajax.php

if ($_POST['brand_car']) {
    $sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
    $req = $dbh->prepare($sql);
    $req->bindValue(':idBrand', $_POST['brand_car']);
    $req->execute();
    $model = array();
    foreach  ($req as $row){
            $model[] = array(
                            'id' => $row['id_model_car'],
                            'modele' => $row['name_model_car']                            
                        );
    }
    echo json_encode($model);
}

的jQuery

$('#brand_car').change(function () { 
var id = $(this).children(":selected").attr("id");
if(id!=0)
    $.ajax({
        url: '/js/ajax.php',
        dataType: 'json',
        type: "POST",
        data: {brand_car: id},
        success: function(data){          
            $('#model_car').html('<option id="0" value="">choose the model</option>');
            if (data.length > 0) {
                data.forEach(function (elem) {
                $('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
            });
         }}
    });

});

XHTML + PHP

<select id="brand_car" name="brand_car">
    <?php
    $sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
    $req = $dbh->query($sql);

    foreach  ($req as $row) {
        $val=$row['id_brand_car'];
        echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
            if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
        echo ' >'.$row['nom_brand_car'].'</option>';
    }
    ?>
</select>
<select id="model_car" name="model_car">
    <option></option>
</select>

1 个答案:

答案 0 :(得分:0)

有多种方法可以修复它。

jQuery Approach

我认为最简单的方法是折射你的change()并从更改事件中分离ajax调用,如下所示:

$('#brand_car').change(function () { 
   var id = $(this).children(":selected").attr("id");
   getModels(id, 0);
}
function getModels(id, select) {
    if(id!=0)
        $.ajax({
           url: '/js/ajax.php',
           dataType: 'json',
           type: "POST",
           data: {brand_car: id},
           success: function(data){          
               $('#model_car').html('<option id="0" value="0">choose the model</option>');
           if (data.length > 0) {
                 data.forEach(function (elem) {
                     $('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
                 });
                 $('#model_car').val(select);
           }}
    });
}

这允许您通过调用getModels()进行AJAX调用。所以你要做的就是叫它:

<select id="brand_car" name="brand_car">
<?php
    $sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
    $req = $dbh->query($sql);

    foreach  ($req as $row) {
        $val=$row['id_brand_car'];
        echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
            if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
                 echo ' >'.$row['nom_brand_car'].'</option>';
    }

?>
</select>
<select id="model_car" name="model_car">
    <option></option>
</select>

最后标记:

<?php
    echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>

这样代码也更容易测试。这不是一个完美的解决方案,您一定要考虑使用$(function(){});来确保文档准备就绪。 AJAX请求还需要时间来完成,因此当页面加载时,模型不会立即出现。

PHP方法

或者,您可以考虑重用AJAX代码。将其包装成一个函数:

function getModels($dbh, $brand_car) {
   // I know nothing about your design, but globals are no good
   $sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
   $req = $dbh->prepare($sql);
   $req->bindValue(':idBrand', $brand_car);
   $req->execute();
   $model = array();
   foreach  ($req as $row){
        $model[] = array(
                        'id' => $row['id_model_car'],
                        'modele' => $row['name_model_car']                            
                    );
   }
   return $model;
}

AJAX.php

if ($_POST['brand_car']) {
    echo json_encode(getModels($dbh, $_POST['brand_car']));
}

在您的XHTML + PHP中

<select id="model_car" name="model_car">
   <?php
       foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
              echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
       }
   ?>
</select>

PS。您的$_SESSION['brand_car']似乎永远不会更新。