我正在尝试根据第一个下拉列表中给出的选择动态加载第二个选择下拉列表。我试着从这里给出的一个例子,但似乎无法让它自己工作。警报输入值已更改显示但输入值已更改2消息未显示。这里的原始示例:PHP MYSQL dynamic select box
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<select id="select1" onchange="createSelect2()">
<option value="">Select sth</option>
<option value="1">1st option</option>
<option value="2">2nd option</option>
<option value="3">3rd option</option>
</select>
<select id="select2" onchange="selectSelect2">
<option value="">Select from select1 first</option>
</select>
<script>
$('#select1').change(createSelect2);
$('#select2').change(selectSelect2);
function createSelect2(){
alert("The input value has changed.") ;
var option = $(this).find(':selected').val(),
dataString = "option="+option;
if(option != '')
{
alert("The input value has changed 2. The new value is: " + option);
$.ajax({
type : 'GET',
url : 'http://www.mitilini-trans.gr/demo/test.php',
data : dataString,
dataType : 'JSON',
cache: false,
success : function(data) {
var output = '<option value="">Select Sth</option>';
$.each(data.data, function(i,s){
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
$('#select2').empty().append(output);
},
error: function(){
console.log("Ajax failed");
}
});
}
else
{
console.log("You have to select at least sth");
}
}
function selectSelect2(){
var option = $(this).find(':selected').val();
if(option != '')
{
alert("You selected: "+option);
}
else
{
alert("You have to select at least sth");
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
脚本似乎是正确的。 你只是忘了添加jQuery库。
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<head>