使用jquery / ajax的动态填充下拉列表

时间:2018-08-17 03:07:42

标签: javascript jquery ajax

我正在尝试根据所选的第一个列表值动态填充下拉列表。

注意:两个下拉列表都是多选下拉列表:

这是我的下拉菜单的代码:

<select id="dis" name="dis[]" onChange="AjaxFunction();" class="form-control selectpicker show-menu-arrow" multiple  title="Select a City or Division">
  // my discrictes goes here  
</select>

<select id="zone" name="zone[]" class="form-control  show-menu-arrow" multiple  title="Choose Educational Zone" ></select>

为此,我发现了AjaxFunction() JavaScript函数。如下所示:

function AjaxFunction(){
  var httpxml;
  try {
    // Firefox, Opera 8.0+, Safari
    httpxml=new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      httpxml=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        httpxml=new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

  function stateck() {
    if(httpxml.readyState==4) {
      var myarray = JSON.parse(httpxml.responseText);
      // Before adding new we must remove previously loaded elements
      for(j=document.getElementById('s2').length-1;j>=0;j--) {
        document.getElementById('s2').remove(j);
      }

      for (i=0;i<myarray.data.length;i++) {
        var optn = document.createElement("OPTION");
        optn.text = myarray.data[i].name_si;
        optn.value = myarray.data[i].zone_id;  
        document.getElementById('s2').options.add(optn);
      } 
    }
  }

  var str='';
  var s1ar=document.getElementById('s1');
  for (i=0;i< s1ar.length;i++) { 
    if(s1ar[i].selected) {
      str += s1ar[i].value + ','; 
    }
  } 
  //alert (s1ar);

  var str=str.slice(0,str.length -1); // remove the last coma from string
  //alert(str);

  //alert(str);
  var url="../includes/dropdown-zones.php";

  url=url+"?dis_id="+str;
  url=url+"&sid="+Math.random();
  //alert(url);
  httpxml.onreadystatechange=stateck;
  httpxml.open("GET",url,true);
  //httpxml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpxml.setHeader('Content-type', 'application/json');

  httpxml.send(null);
}

我的问题是,现在我需要将上述函数转换为jquery,因为我正在为此寻找jQuery / Ajax解决方案:

这是我使用jQuery尝试的方式:

$('#dis').on('change',function() {
  var str='';
  var s1ar=document.getElementById('dis');
  for (i=0;i< s1ar.length;i++) { 
    if(s1ar[i].selected) {
      str += s1ar[i].value + ','; 
    }
  } 

  var str=str.slice(0,str.length -1);
  var url="../includes/dropdown-zones.php";
      url=url+"?dis_id="+str;
      url=url+"&sid="+Math.random();

  $.ajax({
    type: "GET",
    url: url, 
    contentType: "application/json; charset-utf-8",
    dataType: "json",
    success: function(data) {
      $('#zone').empty();
      $('#zone').append("<option value=''>- Select Zone-</option>");
      $.each(data, function(i,item){
        var selecting; 
        if (selected === data[i].id) {
          selecting = ' selected="selected"'; 
        } else {
          selecting = '';
        }
        $('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
      });
    }, 
    complete: function() {}
  }); 
});

但是对我不起作用。有人可以帮我解决这个问题吗?

谢谢

1 个答案:

答案 0 :(得分:1)

代码很好,我无法定义“ selected”错误

您可以看到if(selected === data[i].id)此处的“选定”变量未从第一个下拉列表分配给选定值。

您还需要从第一个下拉列表中删除onChange="AjaxFunction();",因为现在您正在使用jQuery

检查以下代码:

$(document).ready(function(){

	$('#dis').on('change',function() {
		
	  var str='';
	  var s1ar=document.getElementById('dis');
	  for (i=0;i< s1ar.length;i++) { 
		if(s1ar[i].selected) {
		  str += s1ar[i].value + ','; 
		}
	  }
	  
	  var str=str.slice(0,str.length -1);
	  var url="dropdown-zones.php";
		  url=url+"?dis_id="+str;
		  url=url+"&sid="+Math.random();

	  $.ajax({
		type: "GET",
		url: url, 
		contentType: "application/json; charset-utf-8",
		dataType: "json",
		success: function(data) {
		  $('#zone').empty();
		  $('#zone').append("<option value=''>- Select Zone-</option>");
		  $.each(data, function(i,item){
			var selecting=''; 
			if ($('#dis').val().findIndex(x => x==data[i].id)>=0) {
			  selecting = ' selected="selected"'; 
			} else {
			  selecting = '';
			}
			$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
		  });
		}, 
		complete: function() {}
	  }); 
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="dis" class="form-control selectpicker show-menu-arrow" multiple  title="Select a City or Division">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

<select id="zone" class="form-control  show-menu-arrow" multiple  title="Choose Educational Zone" ></select>

结果是这样的:

jSon文件的值为:

[{
        "id": 1,
        "name": "New"
    },
    {
        "id": 2,
        "name": "Open"
    },
    {
        "id": 3,
        "name": "Close"
    }
]