如何使用PHP ajax JQUERY创建3个依赖的下拉列表?

时间:2017-03-15 07:09:54

标签: javascript php jquery mysql ajax

我有一个网页,其中包含3个下拉列表,其中包含从MYSQL数据库中检索的数据。

我想让这三个下拉列表相互依赖,用户从第一个下拉列表中选择,并根据用户的选择,第二个下拉列表显示与第一个下拉列表相关的数据,同样的事情发生在第二个和第三个下拉列表。

我写了一段代码,但没有任何事情发生在哪里,我的错误以及如何修复它?

javascript代码:

<script type="text/javascript">

// make Dropdownlist depend on each other
$(document).ready(function(){
  $('#site_name').on('change'function(){
    var SITENAME = $(this).val();

   if(SITENAME){
    $.ajax({
     url: 'search_info_location.php',
     type:'POST',
     data:'site_name='+SITENAME,
     dataType: 'json',
     success:function(html){

        $('#owner_name').html(html);
        $('#Company_name').html('<option value="">Select Owner Name</option>');
     }

    });
   }
   else{
      $('#owner_name').html('<option value="">Select Site Name first</option>');
      $('#Company_name').html('<option value="">Select Owner Name first</option>'); 
   }
  });

  $('#owner_name').on('change',function(){
     var OWNERNAME = $(this).val();
     if(OWNERNAME){
        $.ajax({
           type:'POST',
           url:'search_info_location.php',
           data:'owner_name='+OWNERNAME,
           success:function(html){
             $('#Company_name').html(html);
           }

        });
     }else{
        $('#Company_name').html('<option value="">Select Owner Name first</option>');
     }

  });

});

注意:我使用 json_encode()

从数据库中提取数据作为对象而不是转换为json对象

完成代码:

   <?php
        /*
        Template Name: search info_location
        */

        get_header();
          ?>

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Markers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <script src="jquery.min.js"></script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCquey2tCZ32jLJJDEEi2D7_RnXXyj9RTI&callback=initMap">
    </script>
     <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 400px;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

    </style>

  </head>
  <body>
    <div id="map"></div>


  <?php
        // code for submit button action
        global $wpdb, $site_name;
    //variables that handle the retrieved data from mysql database based on the ID of the variable in HTML (select)



    if(isset($_POST['query_submit']))
    {


       if(isset($_POST['site_name'])) 
          { 
           $site_name=$_POST['site_name'];

          }
          else { $site_name=""; }


        if(isset($_POST['owner_name'])) 
         {
          $owner_name=$_POST['owner_name']; 

         } 
         else { $owner_name=""; }

         if(isset($_POST['Company_name'])) 
         {
          $company_name=$_POST['Company_name'];

         } 
         else { $company_name=""; }

        if(isset($_POST['Subcontractor_name'])) 
        { 
         $Subcontractor_name=$_POST['Subcontractor_name']; 

        }
        else { $Subcontractor_name="";}



 //   var_dump($site_name);

$sql = $wpdb->prepare("select i.siteID
     , i.siteNAME
     , i.equipmentTYPE
     , c.latitude
     , c.longitude
     , c.height 
     , o.ownerNAME
     , o.ownerCONTACT
     , x.companyNAME
     , y.subcontractorCOMPANY
     , y.subcontractorNAME
     , y.subcontractorCONTACT
  from site_info i
  LEFT  
  JOIN owner_info o
    on i.ownerID = o.ownerID
  LEFT  
  JOIN company_info x
    on i.companyID = x.companyID
  LEFT 
  JOIN subcontractor_info y
    on i.subcontractorID = y.subcontractorID
    LEFT JOIN site_coordinates2 c
    on i.siteID=c.siteID 
    where 
    i.siteNAME = %s
    AND 
    o.ownerNAME = %s
    AND 
    x.companyNAME = %s
   ",$site_name,$owner_name,$company_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);

    echo "<br>";
    echo "<br>";
//echo $sql;

//    var_dump($_POST['site_name']);

// table that will dsiplay the results based on the user's selection //
echo "<table class='t1' width='30%'> ";
echo     "<tr>";
echo           "<th>Site Name</th>";
echo           "<th>Owner Name</th>";
echo           "<th>Company Name</th>";
echo           "<th>Subcontractor Name</th>";
echo           "<th>Site ID</th>";
echo           "<th>Equipment Type</th>";
echo           "<th> Lattitude</th>";
echo           "<th>Longitude </th>";
echo           "<th> Height</th>";
echo           "<th> Owner Contact</th>";
echo           "<th> Sub Contact</th>";
echo           "<th> Sub company Name</th>";
echo   "</tr>";  


foreach ($query_submit as $obj) {

echo   "<tr>";       
echo         "<td>".$obj->siteNAME."</td>";
echo         "<td>".$obj->ownerNAME."</td>";
echo         "<td>".$obj->companyNAME."</td>";
echo         "<td>".$obj->subcontractorNAME."</td>";
echo         "<td>".$obj->siteID."</td>";
echo         "<td>".$obj->equipmentTYPE."</td>";
echo         "<td>".$obj->latitude."</td>";
echo         "<td>".$obj->longitude."</td>";
echo         "<td>".$obj->height."</td>";
echo         "<td>".$obj->ownerCONTACT."</td>";
echo         "<td>".$obj->subcontractorCONTACT."</td>";
echo         "<td>".$obj->subcontractorCOMPANY."</td>";
echo  "</tr>";            
//$arrayOBJ = (array)$obj;
echo json_encode($obj);
//var_dump($arrayOBJ);
}    

?>

<script type="text/javascript">

// make Dropdownlist depend on each other
$(document).ready(function(){
  $('#site_name').on('change'function(){
    var SITENAME = $(this).val();

   if(SITENAME){
    $.ajax({
     url: 'search_info_location.php',
     type:'POST',
     data:'site_name='+SITENAME,
     dataType: 'json',
     success:function(html){

        $('#owner_name').html(html);
        $('#Company_name').html('<option value="">Select Owner Name</option>');
     }

    });
   }
   else{
      $('#owner_name').html('<option value="">Select Site Name first</option>');
      $('#Company_name').html('<option value="">Select Owner Name first</option>'); 
   }
  });

  $('#owner_name').on('change',function(){
     var OWNERNAME = $(this).val();
     if(OWNERNAME){
        $.ajax({
           type:'POST',
           url:'search_info_location.php',
           data:'owner_name='+OWNERNAME,
           success:function(html){
             $('#Company_name').html(html);
           }

        });
     }else{
        $('#Company_name').html('<option value="">Select Owner Name first</option>');
     }

  });

});




     var map,currentPopup;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: new google.maps.LatLng(33.888630, 35.495480),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
        var icons = {
          parking: {
            icon: iconBase + 'parking_lot_maps.png'
          },
          library: {
            icon: iconBase + 'library_maps.png'
          },
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };




        function addMarker(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,

            //icon: icons[feature.type].icon,
            map: map
          });

          var popup = new google.maps.InfoWindow({
                   content: '<b>Site ID :</b> ' + feature.info +'<br></br>' 
                   + '<b> Site Name :</b>' + feature.site_name +'<br></br>'  
                   + '<b>Coordinates :</b> '+ feature.position +'<br></br>' 
                   + '<b>height :</b> ' + feature.height,
                   maxWidth: 300
                });

          google.maps.event.addListener(marker, "click", function() {
                    if (currentPopup != null) {
                        currentPopup.close();
                        currentPopup = null;
                    }
                    popup.open(map, marker);
                    currentPopup = popup;
                });
                google.maps.event.addListener(popup, "closeclick", function() {
                    map.panTo(center);
                    currentPopup = null;
                });
        }



        var features = [
        <?php
            $prependStr ="";
            foreach( $wpdb->get_results("select c.siteID, c.latitude, c.longitude, c.height 
                                         , i.siteNAME
                                         FROM site_coordinates2 c LEFT 
                                         JOIN site_info i
                                         on c.siteID = i.siteID 
                                         where i.siteNAME = '".$site_name."'", OBJECT) as $key => $row) {
               $latitude = $row->latitude;
               $longitude = $row->longitude;
               $siteid = $row->siteID;
               $height = $row->height;
               $siteName = $row->siteNAME;
           echo $prependStr;
       ?>
{
    position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
    info:'<?php echo $siteid;?>',
    height: '<?php echo $height;?>',
    site_name: '<?php echo $siteName;?>',

}
<?php
$prependStr =",";
}
?>
        ];



        for (var i = 0, feature; feature = features[i]; i++) {

          addMarker(feature);
       }
}

         </script>
 <?php        



echo "</table>";

 }

?>    

<!--  the below part  of code work as it should   --!>
    <!--create  dropdown list site names-->

    <form method ="post" action ="" name="submit_form">
        <table border="0" width="30%">
            <tr>
               <td>Site Name</td>
               <td>Owner Name</td>
               <td>Company Name</td>
               <td>Subcontractor Name</td>
             </tr>
             <tr>
               <td><select id="site_name"  name = "site_name">

                 <?php


                     $query_site_name =$wpdb->get_results("select DISTINCT siteNAME  from site_info");
                      foreach($query_site_name as $site_name)
                      {
            //           $site_name = (array)$site_name;
                       echo "<option value = '".$site_name ->siteNAME."'>".  $site_name->siteNAME."</option>";
                      } 
                 ?>

                <!--create  dropdown list owner names-->
                </select></td>

                <td><select id="owner_name"  name ="owner_name">
                <?php
                 global $owner_name;
                      $query_owner_name =$wpdb->get_results ("select DISTINCT ownerNAME  from owner_info");
                      foreach($query_owner_name as $owner_name)
                      {
          //               $owner_name = (array)$owner_name;
                         echo "<option value = '".$owner_name->ownerNAME."'>".  $owner_name->ownerNAME."</option>";
                      } 
                  ?>
                </select></td>

                <!--create  dropdown list Company names-->
                </select></td>

                <td><select id="Company_name"  name ="Company_name">
                <?php 
                global $Company_name;
                     $query_Company_name =$wpdb->get_results ("select DISTINCT companyNAME  from company_info");
                     foreach($query_Company_name as $Company_name)
                     {
        //               $Company_name = (array)$Company_name;
                       echo "<option value = '".$Company_name->companyNAME."'>".  $Company_name->companyNAME."</option>";
                     }  
                 ?>
                </select></td>

                <!--create  dropdown list Subcontractor names-->
                </select></td>

                <td><select id="Subcontractor_name"  name ="Subcontractor_name">
                <?php 
                global $Subcontractor_name;
                    $query_Subcontractor_name =$wpdb->get_results ("select DISTINCT subcontractorNAME  from subcontractor_info");
                     foreach($query_Subcontractor_name as $Subcontractor_name)
                     {
      //                 $Subcontractor_name = (array)$Subcontractor_name;
                       echo "<option value = '".$Subcontractor_name->subcontractorNAME."}'>".  $Subcontractor_name->subcontractorNAME."</option>";
                      } 
                   ?>
                </select></td>
            <tr>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td>
            <input type ="submit" name="query_submit" value ="Search" />

        </td>
       </tr>

        </table>
    </form>

  </body>
</html>

<?php
get_footer();
?>    

1 个答案:

答案 0 :(得分:1)

尝试以下纯JS实现-

App
var stateObject = {
  "Three Wheelers": {
    "Bajaj": ["Bajaj RE CNG", "Bajaj Diesel"],
    "Atul": ["Piaggo", "Shakti"]
  },
  "Two Wheelers": {
    "Hero": ["Splendor", "CBZ"],
    "Honda": ["Hornet", "CBR"],
  },
  "Car": {
    "Suzuki": ["Swift", "Ciaz", "Baleno", "Dzire", "Brezaa", "Ertiga", "Celerio", "Eco", "Omni", "Alto", "Scross", "Ignis", "WagonR"],
    "Hyundai": ["i20", "i10", "Creat", "Eon", "Xcent", "Santro", "Tucson", "Elatrna"],
    "Volkswagon": ["Jetta", "Polo", "Passata", "Polo", "Tiguan", "Ameo"],
    "Nissan": ["Terrano", "Duster", "Micra", "Sunny"],
    "Honda": ["City", "Verna", "CR-V", "Accord", "BR-V", "Brio", "Amaze", "Jazz"],
    "Ford": ["EcoSports", "Endaviour", "Figo", "Freestyle", "Aspire"],
  }

}
window.onload = function() {
  var stateSel = document.getElementById("stateSel"),
    countySel = document.getElementById("countySel"),
    citySel = document.getElementById("citySel");
  for (var state in stateObject) {
    stateSel.options[stateSel.options.length] = new Option(state, state);
  }
  stateSel.onchange = function() {
    countySel.length = 1; // remove all options bar first
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      countySel.options[0].text = "Select Brand"
      citySel.options[0].text = "Select Modal"
      return; // done   
    }
    countySel.options[0].text = "Select Brand"
    for (var county in stateObject[this.value]) {
      countySel.options[countySel.options.length] = new Option(county, county);
    }
    if (countySel.options.length == 2) {
      countySel.selectedIndex = 1;
      countySel.onchange();
    }

  }
  stateSel.onchange(); // reset in case page is reloaded
  countySel.onchange = function() {
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      citySel.options[0].text = "Please Modal"
      return; // done   
    }
    citySel.options[0].text = "Please Modal"

    var cities = stateObject[stateSel.value][this.value];
    for (var i = 0; i < cities.length; i++) {
      citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
    }
    if (citySel.options.length == 2) {
      citySel.selectedIndex = 1;
      citySel.onchange();
    }

  }
}