根据使用Ajax的另一个Dropdown选择填充下拉列表

时间:2014-02-03 09:29:01

标签: javascript php jquery mysql ajax

我需要根据另一个id选择一个id。 我自己制作了一些东西,但它不起作用,所以我发布了CODE,也许我有一些错误。选择车辆的第一个选项,在第二个选项中选择我选择的车辆的型号。 谢谢!

//The config file

<?php

$host = 'localhost';         
$utilizator = 'stud';         
$parola = 'stud';         
$numebd = 'autodealer';      

$conn = mysql_connect($host, $utilizator, $parola);
if (!$conn) { echo '<h4>Connected!</h4>'; }

if (!mysql_select_db($numebd, $conn)) { 
   echo '<h4>Couldnt connect database : '. mysql_errno(). ' : '. mysql_error().'</h4>'; 
}

mysql_set_charset('utf8', $conn);
?>


//The HTML code

<h2><strong>Vehicle</strong> data</h2>
    <div class="select_wrapper">
    <form action="" method="post" name="anunt" id="f_anunt">
        <label><span>* </span><strong>Manufacturer:</strong></label>
        <select class="select_5" name="marca" id="marca">                           
            <?php
                $result = mysql_query("SELECT id_marca, denumire FROM marci ORDER BY ordine");
                while($row = mysql_fetch_array($result)) {
                    echo ("<option value='".$row['id_marca']."'>".$row['denumire']."</option>");
                }
            ?>
        </select>
        </div>
        <div class="select_wrapper">
        <label><span>* </span><strong>Model: </strong></label>
            <select class="select_5" name="model" id="model">
                <?php                                   
                    $result = mysql_query("SELECT id_model, denumire FROM modele WHERE id_marca=1");
                    while ($row = mysql_fetch_array($result)) {
                        echo ("<option value='".$row['id_model']."'>".$row['denumire']."</option>");
                    }
                ?>
            </select>
        </div>

//The PHP file

<?php
include_once("config.php");

$id_marca = $_POST['id_marca'];

$sir_sql="SELECT id_model, denumire FROM modele WHERE id_marca=$id_marca ";

if ($conn())
    {               
        $result=mysql_query($sir_sql,$conn);

        while ($row = mysql_fetch_array($result))       
           echo ("<option value='".$row['id_model']."'>".$row['denumire']."</option>");

    }
    else 
        die('Comanda incorecta:<br> ' . mysql_error()); 
?>

//The Javascript code

$("#marca").change(get_model);

    function get_model(e)
{
    $.post("ajax_get_model.php",{id_marca:$(this).val()},function(data,status)
        {   
            $("#model").html(data); // pun modelele 
        });
}

1 个答案:

答案 0 :(得分:1)

关于此主题,SO上有几篇帖子。请先阅读这些主题,希望这些有用 -

  1. Populate one dropdown list based on the selection of other dropdown list
  2. jQuery show/hide drop-down options based on another drop-down option
  3. 最后,您可以查看此处的教程,根据下拉选择填充下拉列表...

    Tutorial Here | Demo Here