答案 0 :(得分:1)
因此,对您的问题的纯理论答案将如下所示:
$locations = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if (!isset($locations[$row['country']])
{
$locations[$row['country']] = [];
}
$locations[$row['country']][] = $row['location'];
}
然后,填充国家/地区选择元素:
$countries = array_keys($locations);
foreach ($countries as $country)
{
echo '<option value="' . $country . '">' . $country . '</option>';
}
要使位置映射可用于您的JS代码,只需写下:
var locationsMap = <?php ech json_encode($locations); ?>;
最后,将一个事件监听器附加到country select元素,该元素填充 change 事件上的locations元素,然后就完成了
但在实践中,这只是理论:
使用AJAX,你所要做的就是附加相同的事件监听器(更改country元素),并将选定的值传递给AJAX请求,该请求返回应该用于填充locations元素的值: / p>
<select class="form-control" id="country" name="country" required>
<!-- populate whichever way you want -->
</select>
然后:
document.querySelector('#country').addEventListener('change', function(e)
{
//if you want to support very old browsers
e = e || window.event;
var country = this.options[this.selectedIndex].value;//or .text
var req = new XMLHttpRequest();
req.open('post', 'yourUrl', true);
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function()
{
if (this.readyState===4 && this.status===200)
{//assuming the AJAX request returns the options for locations element:
document.querySelector('#locations').innerHTML = this.responseText;
}
};
req.send('country=' + country);//send selected value
});
//or with jQuery:
$('#country').on('change', function()
{
var data = {country: $(this).val()};
$.ajax({
url: 'yourUrl',
method: 'post',
data: data,
success: function(r)
{
$('#locations').html(r);//<-- something like that
}
});
});
注意:
自从我上次做了一些前端工作以来已经有一段时间了,我把它写在了我的头顶,所以这不是一个可复制的代码片段。它还远没有优化,但它应该足以让你开始。
PS:您在评论中链接到w3schools,您可能想要检查MDN。他们仍然倾向于为所有JS提供更好,更完整的文档
答案 1 :(得分:0)
尝试这样的事情。但是我建议使用AJAX ......
<form method = "post">
<select name="country" onchange="this.form.submit()">
<option value='a'>A</option>
<option value='b'>B</option>
<option value='C'>C</option>
.....
</select>
<select name="location">
<?php
if(isset( $_POST['country'] )){
//code here to fetch relevant data
}
?>
</select>
</form>