我有三个下拉菜单,我希望当我选择第一个下拉菜单的值时,该值不应使用select2库显示在第二个下拉菜单中

时间:2019-03-21 14:17:10

标签: javascript jquery-select2

    <select class="js-example-templating1" id="first_drop">
                <option></option>
              </select>
              <select class="js-example-templating2">
                <option></option>            
              </select>
              <select class="js-example-templating3">
                <option></option>
      </select>

这是Javascript代码

<script>
  var array2;
<?php
  $data = array();
  $query = "select * from user;
  $query_result = query($query);
  $i=0;
  while($row = fetch_array($query_result)) {
    $data[$i]["id"] = $row['user_id'];
    $data[$i]["text"] = $row['user_id']." - ".$row['name'];
    $i=$i+1;
  }
  $data_user =  json_encode($data);
?>
var array1 = <?php echo $data_user; ?>;
function formatState (state) {
  if (!state.id) {
    return state.text;
  }
    var $state = $(
    '<span>' + state.text + '</span>'
  );
  return $state;
};
$(".js-example-templating1").select2({
  data: array1,
  templateResult: formatState
});
  $(".js-example-templating2").select2({
    ajax:{
      url: 'fetch_data.php',
      type:'post',
      dataType: 'json',
      delay: 250,
      data: function(params) {
        var first_drop = parseInt(document.getElementById("first_drop").value);
        return {
          searchTerm: params.term,
          first_drop : first_drop
        };
      },
      processResults: function(response){
        return {
          results: response
        };
      },
      cache: true
    },
});
$(".js-example-templating3").select2({
  data: array1,
  templateResult: formatState
});

fetch_php文件

if (!(isset($_POST['searchTerm']) and isset($_POST['first_drop']))) {
      $query2 = "select * from user";
    }elseif(isset($_POST['searchTerm']) and isset($_POST['first_drop'])){
      $drop_1 = escape_string($_POST['first_drop']);
      $stri = escape_string($_POST['searchTerm']);
      $query2 = "select * from user where user_id != ".$drop_1." and name LIKE '".$stri."%'";
    }elseif(isset($_POST['searchTerm']) and !isset($_POST['first_drop'])){
      $stri = escape_string($_POST['searchTerm']);
      $query2 = "select * from user where name LIKE '".$stri."%'";
    }elseif(!isset($_POST['searchTerm']) and isset($_POST['first_drop'])){
      $drop_1 = escape_string($_POST['first_drop']);
      $query2 = "select * from user where user_id != ".$drop_1;
    }
    $query_result2 = query($query2);
    $i=0;
    while($row2 = fetch_array($query_result2)) {
      $data2[$i]["id"] = $row2['user_id'];
      $data2[$i]["text"] = $row2['user_id']." - ".$row2['name'];
      $i=$i+1;
    }
    echo json_encode($data2);

我面临的问题是,当我选择第一个下拉菜单时,更新将不会显示在第二个下拉菜单中。第二个下拉列表显示所有数据。我检查第一个下拉列表的数据,当打开第二个下拉列表时,该值存在,但仍未更新第二个下拉列表。 fetch_data.php用于ajax调用。使用getElementById提取第一个下拉列表的值。

0 个答案:

没有答案