Tôi đang cố gắng tạo một tập hợp các hộp thả xuống động, sử dụng jQuery/AJAX và PHP/MySQL. Hộp thả xuống đầu tiên sẽ được điền khi trang tải dựa trên các giá trị từ cơ sở dữ liệu. Hộp thả xuống thứ hai sẽ hiển thị một tập hợp các giá trị dựa trên lựa chọn từ hộp thả xuống đầu tiên. Tôi biết đã có những câu hỏi tương tự được yêu cầu ở đây trước đây, nhưng tôi đã không tìm thấy một giải pháp phù hợp với kịch bản của tôi.Cách điền danh sách thả xuống thứ hai dựa trên lựa chọn trình đơn thả xuống đầu tiên bằng cách sử dụng jQuery/AJAX và PHP/MySQL?
Truy vấn của tôi để tạo danh sách các giá trị được mã hóa JSON cho menu thả xuống thứ hai đang hoạt động, nhưng tôi đang gặp sự cố khi đưa nó vào phần tử biểu mẫu thả xuống thực tế. Bất kỳ ý tưởng nào về việc tôi sẽ sai ở đâu.
Javascript:
<script>
$().ready(function() {
$("#item_1").change(function() {
var group_id = $(this).val();
$.ajax({
type: "POST",
url: "../../db/groups.php?item_1_id=" + group_id,
dataType: "json",
success: function(data){
//Clear options corresponding to earlier option of first dropdown
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each(data.subjects, function(){
$('select#item_2').append('<option value="'+$(this).attr('group_id')+'">'+$(this).attr('name')+'</option>');
});
$('select#item_2').focus();
},
beforeSend: function(){
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Loading...</option>');
},
error: function(){
$('select#item_2').attr('disabled', true);
$('select#item_2').empty();
$('select#item_2').append('<option value="0">No Options</option>');
}
})
});
});
</script>
HTML:
<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
<option value="">Select</option>
<?php
$sth = $dbh->query ("SELECT id, name, level
FROM groups
WHERE level = '1'
GROUP by name
ORDER BY name");
while ($row = $sth->fetch()) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'."\n";
}
?>
</select>
<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />
</select>
PHP:
<?php
require_once('../includes/connect.php');
$item_1_id = $_GET['item_1_id'];
$dbh = get_org_dbh($org_id);
$return_arr = array();
$sth = $dbh->query ("SELECT id, name, level
FROM groups
WHERE level = '2'
AND parent = $item_1_id
GROUP by name
ORDER BY name");
while ($row = $sth->fetch()) {
$row_array = array("name" => $row['name'],
"id" => $row['id']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
mẫu JSON Output:
[{"name":"A","id":"0"},{"name":"B","id":"1"},{"name":"C","id":"2"}]
Bạn có nhận được bất kỳ lỗi JS nào không? –
Bạn có thể cung cấp ví dụ về JSON của mình không? –
Firebug đang hiển thị "đối tượng là undefined, length = object.length" cho tập lệnh jQuery, sau khi hộp thả xuống đầu tiên được thay đổi. Không có lỗi khi tải trang. – Michael