1. 程式人生 > >省市聯動js與php互動

省市聯動js與php互動

js 部分程式碼 - ajax

<script>
function f1(){
  // sele1=document.getElementById('a').value
  var sele1 = $('#a').val();
  $.ajax({
    type : "post",
    url : "ajax.php",
    data : {"sele1" : sele1},
    success : function(msg){
      var option = '';
      for(i in msg){
        option+= "<option value='"+msg[i]['region_id']+"'>"+msg[i]['region_name']+"</option>";
      }
      $('#b').html(option);
    },
    dataType : "json"
  });
}
</script>

php部分程式碼

if ($_POST['sele1']==0) {
	$as = $conn->query('select * from xfc_region where parent_id = '.$_POST['sele1']);
	$aa = array();
	while ($ad = mysqli_fetch_array($as)) {
		$aa[] = $ad;
	}
// var_dump($aa);
}

if ($_POST['sele1']==0) {
	$a1 = $conn->query('select region_id from xfc_region where parent_id = '.$_POST['sele1']);
	$a2 = mysqli_fetch_array($a1);
	$a3 = $conn->query('select region_name from xfc_region where parent_id = '.$a2['region_id']);
	$ab = array();
	while($ah = mysqli_fetch_array($a3)){
		$ab[]= $ah;
	};
		
	echo json_encode($ab);
}