我有2个下拉菜单。第一个我填充了可能的大陆,并希望第二个下拉菜单包括所有国家,这取决于在第一个菜单中选择的大陆。我只有1个带有列的mysql表:continent - >国家。目前,即使选择了一个大陆,也有来自各大洲的所有国家。谢谢您的帮助! 这是我的代码:
HTML
<input type="text" class="autosuggest" id="autosuggest2" placeholder="Select Country...">
<div class="country">
<ul class="result" id="result2"></ul>
</div>
<input type="text" class="autosuggest" id="autosuggest3" placeholder="Select Area...">
<div class="area">
<ul class="result" id="result3"></ul>
</div>
jQuery / Ajax
$(document).ready(function() {
$('#autosuggest1').keyup(function() {
var continent = $(this).attr('value');
$.post('php/dropdown.php', {continent:continent}, function(data) {
$('#result1').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest1').attr('value', result_value);
$('#result1').html('');
$('#result1').focusout('');
});
});
});
$('#autosuggest2').keyup(function() {
var country = $(this).attr('value');
$.post('php/dropdown.php', {country:country}, function(data) {
$('#result2').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest2').attr('value', result_value);
$('#result2').html('');
$('#result2').focusout('');
});
});
});
});
PHP
require_once '../connect/connectdropdown.php';
if (isset($_POST['continent']) == true && empty($_POST['continent']) == false) {
$continent = mysql_real_escape_string($_POST['continent']);
$query = mysql_query("SELECT DISTINCT `continent` FROM `area` WHERE `continent` LIKE '$continent%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['continent'], '</li>';
}
}
if (isset($_POST['country']) == true && empty($_POST['country']) == false) {
$country = mysql_real_escape_string($_POST['country']);
$query = mysql_query("SELECT DISTINCT `country` FROM `area` WHERE `country` LIKE '$country%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['country'], '</li>';
}
}
答案 0 :(得分:1)
我想知道你是否还在这。无论如何我会建议几件事:
只做一个查询,将其传递给json,并将其提供给javascript。
PHP
require_once '../connect/connectdropdown.php';
$id=0;
$result=array();
$query = mysql_query("SELECT * FROM `area` ");
while (($row = mysql_fetch_assoc($query)) !== false) {
$result[$id]=$row;
$id++;
}
echo json_encode($result);
的Javascript
$(document).ready(function() {
var $mysqlData;
$.post('php/dropdown.php', {continent:continent}, function(data) {
//Json Data from server:
alert('JSON data: '+data)
//you can transform the data from PHP-Json to Javascript Object
$mysqlData = jQuery.parseJSON(data)
//now you can access your data like:
alert ('My first continent: '+$mysqlData[0].continent+' and it\'s first country: '+$mysqlData[0].country)
});
$('#autosuggest1').keyup(function() {
//Now you can use $mysqlData inside your logic
})
$('#autosuggest2').keyup(function() {
//You can use $mysqlData here too
})
});
我没有测试这段代码,可能会出现一些错误,但我建议你采用这种逻辑。