看板 PHP 關於我們 聯絡資訊
假設資料庫有以下的表: 表 select_a : id int 編號 value text 顯示文字 表 select_b : id int 編號 a_id int 對應到 select_a 的編號 value text 顯示文字 <?php // 建立資料庫連線 $db = new PDO("mysql:host=localhost;dbname=web", "user", "pass"); // 判斷是否為 select_b 請求 if (isset($_GET["q"]) && is_numeric($_GET["q"])) { // 取得 select_b 的資料 $id = (int) $_GET["q"]; $query = $db->prepare( "SELECT `id`, `value` FROM `select_b` WHERE `a_id` = :id" ); $query->bindParam(":id", $id, PDO::PARAM_INT); $query->execute(); $data = $query->fetchAll(); // 整理資料 $json_obj = array(); foreach ($data as $d) { $json_obj[] = array( "id" => $d["id"], "value" => $d["value"] ); } $json = json_encode($json_obj); // 回傳資料 header("Content-Type: application/json"); header("Content-Length: " . strlen($json)); echo($json); exit(); } // 取得 select_a 的資料 $query = $db->prepare("SELECT `id`, `value` FROM `select_a`"); $query->execute(); // 整理成 HTML $select_a = ""; while (false !== ($data = $query->fetch()) { $id = $data['id']; $value = $data['value']; $select_a .= "<option value=\"$id\">$value</option>"; } header("Content-Type: text/htm; charset=utf-8"); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Form Select 範例</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> $(function () { // 當 select_a 改變時 $(document.form_main.select_a).change(function () { // 取得 select_b 資料 $.getJSON( window.location.pathname + "?q=" + this.value + "&dummy=" + $.now(), function(data) { // 把資料填入 select_b var select = $(document.form_main.select_b); var options = select.attr('options'); for (var i in data) { options[i] = new Option(data.id, data.value); } // 讓 select_b 選擇第一項 select.val(0); }); }); }); }); </script> </head> <body> <form name="form_main"> <select name="select_a"><?php echo($select_a); ?></select> <select name="select_b"></select> </form> </body> </html> (找時間再來上色好了# -- ` ◥◣◢◣◢◣ ◢▏。 ○ ο ° ██◤ █◤◥◤█ o ° ◤ ◥ █ █ ˍ ◤◤ ◢◤ ◢◤██◣ ◢ ◢◤ ◤ingsay ◢███ ζ ) ) mt.rmstudio.tw [email protected] ◤◤ wnqui -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 101.12.72.109