PHP和Jquery创建具有可能的条件行为的多个动态选择列表

时间:2018-09-08 08:02:48

标签: javascript php jquery

标题有点多,所以让我分解一下。我要在这里完成的任务是从select 1(onChange)中选择一个选项,以从外部php脚本中检索select 2的预建选择。对于2-> 3和3-> 4也是一样。我知道该怎么做,也许效率不高,但是我能做到。

我遇到的问题是,第三个选择并不总是一个选项。这是一个问题,因为第四选择是我需要的最终结果。在这种情况下,第二个选择将给我ID来创建选择4。有道理吗?

HTML:

<td>
    <select name="collectionID" id="bpCollection" class="form-control">
        <option value="">Select Collection</option>
            <?PHP echo optionsFromDatabase();?>
    </select>
</td>
<td><select name="bpClass"id="bpClass" class="form-control"></select></td>
<td><select name="bpFaction"id="bpFaction" class="form-control"></select></td>
<td><select name="bpID"id="bpID" class="form-control"></select></td>

JQUERY:

<script>

    $("#bpCollection").change(function() {
        $("#bpClass").load("inc/api/auto.php?type=class&choice=" + $("#bpCollection").val());
    });

    $("#bpClass").change(function() {
        $("#bpFaction").load("inc/api/auto.php?type=faction&choice=" + $("#bpClass").val());
    });

    $("#bpFaction").change(function() {
        $("#bpID").load("inc/api/auto.php?type=blueprint&choice=" + $("#bpFaction").val());
    });


</script>

如前所述,这确实可以正常工作。

Auto.php

$group = $db->escape($_GET['type']);
$choice = $db->escape($_GET['choice']);

$list = ''; 

switch ($group) { 

    case 'blueprint':

        $db->where('marketGroupID',$choice);
        $db->orderBy('typeName','ASC');
        $map = $db->get('invTypes');

        foreach ( $map as $val ) { 

            $list .= '<option value="'.$val['typeID'].'">'.$val['typeName'].'</option>';

        }

        break;

    default:

        $db->where('parentGroupID',$choice);
        $db->orderBy('marketGroupName','ASC');
        $map = $db->get('invmarketgroups');

        foreach ( $map as $val ) { 

            $list .= '<option value="'.$val['marketGroupID'].'">'.$val['marketGroupName'].'</option>';

        }



}

echo $list;

这很好,除了。 #bpFaction并非总是无法填充的选项,因为#bpClass拥有#bpID的ID选项。我可以选择#bpClass选择选项,并且需要直接跳至#bpID。我认为我遇到的问题的很大一部分是,我没有可视化任何一端的代码以使其正常工作。我是否需要让jquery做到这一点,是否需要更改auto.php,或者两者都更改?

您对如何做到最好有任何想法?

2 个答案:

答案 0 :(得分:0)

在不更改大量代码的情况下执行此操作的最简单方法是使您的开关成为一个函数,建立一个条件,并在满足该条件的情况下使用更改后的参数再次调用它。

$list= myswitch($db, $group, $choice);

function myswitch($db, $group, $choice){
   $list='';
   switch ($group) { 
      case 'blueprint':
      ...
      break;

     default:
        $db->where('parentGroupID',$choice);
        $db->orderBy('marketGroupName','ASC');
        $map = $db->get('invmarketgroups');

       //*** CONDITION HERE ***
       //IF condition met: set new variables
       if($choice === ... && $map === ...)){
          $group="xxx";
          $choice="yyy";

          //call the function again with new values
          $list = myswitch($db, $group, $choice);
          }
      //ELSE create normal list
      else{
          foreach ( $map as $val ) { 
             $list.= ....
             }
          }
   return list;
 }

答案 1 :(得分:0)

我建议将Ajax与上面的JSON结合使用。在这里,我将更深入地介绍如何执行此操作。我将使用州,城市和辖区作为选择框类型来编写此示例。

我们将在PHP中为所有选择框使用一个控制器(就像上面的选择框一样),不同的是我们将重新编写它以返回JSON。我不知道您使用的是什么框架,所以我只写了一个示例:

    // if no state passed in, return list
    if(!$stateId = $request->get('state')) {
        $loadedStatesFromDb = ...; // states loaded from DB

        // if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
        $states = [];
        foreach($loadedStatesFromDb as $state) {
            $states[$state->getId()] = $state->getName();
        }

        // your framework may require a different method of passing json data
        return json_encode([
            'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
            'states' => $states
        ]);
    }

    // if no city passed in, load cities for the selected state
    if(!$cityId = $request->get('city')) {
        $loadedCitiesFromDb = ...; // cities loaded from DB for $stateId

        // if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
        $cities = [];
        foreach($loadedCitiesFromDb as $city) {
            $cities[$city->getId()] = $city->getName();
        }

        // your framework may require a different method of passing json data
        return json_encode([
            'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
            'cities' => $cities
        ]);
    }

    // if no jurisdiction selected, load list
    if(!$jurisdictionId = $request->get('jurisdiction')) {
        $loadedJurisdictionsFromDb = ...; // jurisdictions loaded from DB for $cityId

        // if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
        $jurisdictions = [];
        foreach($loadedJurisdictionsFromDb as $jurisdiction) {
            $jurisdictions[$jurisdiction->getId()] = $jurisdiction->getName();
        }

        // your framework may require a different method of passing json data
        return json_encode([
            'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
            'jurisdictions' => $jurisdictions
        ]);
    }

这就是您的视图的样子(未经测试,但通常是如何执行的):

    <select name="state" id="state-select"></select>
    <select name="city" id="city-select"></select>
    <select name="jurisdiction" id="jurisdiction-select"></select>


    <script type="text/javascript">
        function _load_select_boxes(e) {
            if(
                $("#state-select").val() && $("#city-select").val() && $("jurisdiction-select").val() && // if we have an item selected in all select boxes
                typeof e !== 'undefined' && e.target.id == 'jurisdiction-select' // if the select box that triggered the event is the last one
            ) {
                _select_box_completed('jurisdiction', $("jurisdiction-select").val());
            }

            $.ajax({
                url: '/where/you/load/select/boxes',
                type: 'POST',
                data: $("#state-select, #city-select, #jurisdiction-select").serialize(),
                dataType: 'json', // what server will return
                success: function (data) {
                    if (data.result === 'ok') {
                        if(typeof data.states !== 'undefined') {
                            // no need to reset options for the first select (unless we will be re-loading it without selecting a value)

                            // set select box options using the array of cities
                            for(var stateId in data.states) {
                                var stateName = data.states[stateId];
                                $("#city-select").append('<option value="' + stateId + '">' + stateName + '</option>')
                            }
                        } else if(typeof data.cities !== 'undefined') {
                            // reset select box
                            $('#city-select').find('option').remove();

                            // set select box options using the array of cities
                            for(var cityId in data.cities) {
                                var cityName = data.cities[cityId];
                                $("#city-select").append('<option value="' + cityId + '">' + cityName + '</option>')
                            }
                        } else if(typeof data.jurisdictions !== 'undefined') {
                            if(!data.jurisdictions.length) {
                                // no jurisdictions returned so we reached end
                                _select_box_completed('city', $("#city-select").val());
                            } else {
                                // reset select box
                                $('#jurisdiction-select').find('option').remove();

                                // set select box options using the array of jurisdictions
                                for(var jurisdictionId in data.jurisdictions) {
                                    var jurisdictionName = data.jurisdictions[jurisdictionId];
                                    $("#jurisdiction-select").append('<option value="' + jurisdictionId + '">' + jurisdictionName + '</option>')
                                }
                            }
                        }
                    } else {
                        // handle error for app
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // handle error for app
                }
            });
        }

        function _select_box_completed(type, id) {
            // fired when we have selected as far as we can go
        }

        $(function(){
            // this runs when page finishes loading, so we can load in the defaults and set events on the select boxes
            $("#state-select, #city-select, #jurisdiction-select").on('change', function(e){
                _load_select_boxes(e);
            });

            _load_select_boxes();
        });
    </script>