問題描述
我正在嘗試使用從使用 PHP 和 MySQL 的第一個下拉列表中選擇的值填充第二個下拉列表,并且不刷新頁面.我認(rèn)為這很簡單,但無法使其正常工作,因此非常感謝您的幫助.
I am trying to populate a second dropdown list using the value selected from a first dropdown list using PHP and MySQL, and without refreshing the page. I thought this would be simple but can't get it to work so any help would be much appreciated.
到目前為止,我有以下幾點(diǎn):
So far, I have the following:
HTML 表單 (form.php)
<select name="list1" id="list1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="list2" id="list2">
</select>
JavaScript(在 form.php 中)
<script type="text/javascript">
$("#list1").change(function() {
$("#list2").load("get_list2.php?id=" + $("#list1").val());
});
</script>
get_list2.php
require_once("config.php");
$q1 = mysql_query("SELECT * FROM mytable WHERE id = '$_GET[id]'");
while($row1 = mysql_fetch_assoc($q1)){
echo "<option>".$row1['item']."</option>";
}
謝謝!
推薦答案
就像其他成員所說的,你應(yīng)該使用 PDO(帶有準(zhǔn)備好的語句)而不是 mysql_.
Like other members have says, you should use PDO (with prepared statements) instead of mysql_.
一種可能的實(shí)現(xiàn):
HTML (form.php)
HTML (form.php)
<select name="list1" id="list1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="list2" id="list2"></select>
<script type="text/javascript">
$("#list1").change(function() {
$.ajax({
url : "get_list2.php?id=" + $(this).val(),
type: 'GET',
dataType:'json',
success : function(data) {
if (data.success) {
$('#list2').html(data.options);
}
else {
// Handle error
}
}
});
});
</script>
PHP (get_list2.php)
PHP (get_list2.php)
require_once("config.php");
$id = $_GET['id'];
if (!isset($id) || !is_numeric($id))
$reponse = array('success' => FALSE);
else {
// Where $db is a instance of PDO
$query = $db->prepare("SELECT * FROM mytable WHERE id = :id");
$query->execute(array(':id' => $id));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
$options = "";
foreach ($rows as $row) {
$options .= '<option value="'. $row .'">'. $row .'</option>';
}
$response = array(
'success' => TRUE,
'options' => $options
);
}
header('Content-Type: application/json');
echo json_encode($response);
PS:沒有經(jīng)過測試,但它應(yīng)該可以工作......我猜.
PS : not tested but it should works... I guess.
這篇關(guān)于使用 PHP &MySQL 填充下拉列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!