我正在尝试使用从使用 PHP 和 MySQL 的第一个下拉列表中选择的值填充第二个下拉列表,并且不刷新页面.我认为这很简单,但无法使其正常工作,因此非常感谢您的帮助.
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.
到目前为止,我有以下几点:
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>";
}
谢谢!
就像其他成员所说的,你应该使用 PDO(带有准备好的语句)而不是 mysql_.
Like other members have says, you should use PDO (with prepared statements) instead of mysql_.
一种可能的实现:
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:没有经过测试,但它应该可以工作......我猜.
PS : not tested but it should works... I guess.
这篇关于使用 PHP &MySQL 填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!