我需要在下拉列表中获取一些数据,然后在选择特定类型后,我需要另一个下拉列表来从MySQL获取特定类型的值。
I have this link工作正常,但我无法修改它以接受我数据库中的值。
第一个下拉列表的列是:
Refrigerator
Microwave
TVs
Heaters
然后,当我点击其中一个时,我会在我的其他下拉列表中选择一个新数据,就像我选择了电视一样,第二个下拉列表会带来新的数据,如:
LG
SAMSUNG
VESTEL
...
感谢任何帮助。
答案 0 :(得分:2)
你需要使用类似AJAX的东西,
Jquery / Ajax代码
$(document).ready(function() {
$('#id-of-the-first-drop-list').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#id-of-the-first-drop-list').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'get-data-from-database.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
// I got this from somewhere else on stackoverflow
var myOptions = {
val1 : data[0],
val2 : data[1]
};
var mySelect = $('#id-of-the-second-drop-list');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
});
});
});
现在这里是从数据库获取数据的服务器端代码
PHP代码
<?php
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM table_name WHERE column_name = '$data'"
// MySQL
$results = mysql_query($query);
$data = array();
$i = 0;
while($row = mysql_fetch_array($results)) {
data[i] = row['column_name'];
$i++;
}
echo json_encode($data);
?>
此代码未经过测试,可能有错误,但这是一般性的想法。我希望它有所帮助。