作者a60301 (mingtsay〃小喵)
看板PHP
标题Re: [请益] select如何动态取得资料库?
时间Thu Aug 1 13:56:32 2013
假设资料库有以下的表:
表
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 ° ∥★
★∥ 。 ● ● ◤ ◥ █ █ ∥ ◢╱﹋◣ 。 ∣★
★∣ ◥ˍ ◤◤ ◢◤ ◢◢◤██◤ ◣ ◢╱ ● ︶ ( ∥★
★∥ ( ◢◤ ◤ing ∥say ◢███ ╰ ◤ ζ ) ∣★
★│ ) mt.rmstudio.tw ︾ [email protected] ◤ ◥◢ ◤◤ wnqui ∥★
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 101.12.72.109