目次 |
---|
・コンボボックスを連携するには ・コンボボックスを連携するサンプル |
■index.html <script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(function(){ $('#SearchWordFormPref').change( function(){ $.ajaxSetup({scriptCharset:'utf-8'}); $('#SearchWordFormCity').empty(); var select = document.getElementById("SearchWordFormCity"); var i = 0; select.options[i++] = new Option("すべて表示", ""); var prefId = $(this).val(); if (prefId == "") { return; } $.getJSON( //第一引数:JSONのURL 'city.php', //第二引数:RESTパラメータ { 'p' : prefId }, //第三引数:コールバック関数 function(json) { var select = document.getElementById("SearchWordFormCity"); var i = 0; select.options[i++] = new Option("すべて表示", ""); for (key in json) { select.options[i++] = new Option(json[key].City, json[key].City); } } ); } ); }); </script> <img src="img/pref.gif" alt="都道府県" /> <select name="data[SearchWordForm][pref]" id="SearchWordFormPref"> <option value="">すべて表示</option> <option value="北海道">北海道</option> <option value="青森県">青森県</option> <option value="岩手県">岩手県</option> <option value="宮城県">宮城県</option> <option value="秋田県">秋田県</option> <option value="山形県">山形県</option> </select> <img src="img/city.gif" alt="市区町村" /> <select name="data[SearchWordForm][city]" id="SearchWordFormCity"> <option value="">すべて表示</option> </select> </pre> ■city.php <?php $pref = $_GET["p"]; // $host = ''; $user = ''; $pass = ''; $name = ''; $conn = mysql_connect( $host, $user, $pass ); if ( !$conn ) { die( '接続できませんでした: ' . mysql_error() ); } mysql_select_db( $name, $conn ); // $sql = " SELECT" . " pref_id" . " ,pref" . " ,city_id" . " ,city" . " FROM" . " cities" . " WHERE" . " pref = '" . $pref . "'" . " ORDER BY" . " city_id"; $result = mysql_query( $sql ); $profile_list = array(); $profile_data = array(); if ( mysql_num_rows($result) == 0 ) { $profile_data = array( "PrefId" => '-' ,"Pref" => '-' ,"CityId" => '-' ,"City" => '-' ); array_push($profile_list, $profile_data); } else { while ( $data = mysql_fetch_assoc($result) ) { $profile_data = array( "PrefId" => $data['pref_id'] ,"Pref" => $data['pref'] ,"CityId" => $data['city_id'] ,"City" => $data['city'] ); array_push($profile_list, $profile_data); } } $profile_json = json_encode( $profile_list ); header('Content-type: application/json; charset=UTF-8'); echo $profile_json; ?>