본문 바로가기
Web Program/Html Lecture

Ajax 를 이용한 하위 Select 상자 동적 변경.

by 현이빈이 2013. 2. 21.
반응형

Ajax를 이용한 Select 상자 동적 구성

JQuery 를 이용한 방법도 있지만 php 에서 html 소스를 모두 만들수 있다면 아래와 같은 간단한 방법도 있다.

 

html 소스

 

<script>
function select_category(c_name)
{
 if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
  }
 else
  {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
 xmlhttp.onreadystatechange=function()
  {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     document.getElementById("select_category").innerHTML=xmlhttp.responseText;
    }
  }
 xmlhttp.open("GET","get_subcategory.php?c_name=" + c_name,true);
 xmlhttp.send();
}
</script>

 

<select name='category'  onchange='select_category(this.value)'>
 <option value='1'>커뮤니티</option>
 <option value='2'>동영상</option>
 <option value='3'>기타문의</option>
</select>

<div name='select_category' id='select_category'> </div>

 

 

select_category.php

<select name="sub_category">  
<?
 for ($i=0; $i < count($category_arr[$c_name]); $i++) {
?>
 <option value="<?=$category_arr[$c_name][$i]?>"><?=$category_arr[$c_name][$i]?></value>
<?  
  }
?>
</select>

 

 

반응형