我正在尝试通过ajax将数据从我的数据库提取到drop_down_list1。并将其显示给下一个drop_down_list2
。我遵循几乎完全相同的事情,就像在youtube tutorial中一样,但似乎没有用。
以下是代码:
test.php的
<?php
include("connection.php");
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/JavaScript">
function State(){
$('#stateddl').empty();
$('#stateddl').append("<option>Loading...</option>");
$('#districtddl').append("<option value='0'> - </option>");
$.ajax({
type:"POST",
url:"custom2.php",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
$('#stateddl').empty();
$('#stateddl').append("<option value='0'>-</option>");
$.each(data,function(i,item){
$('#stateddl').append('<option value="'+ data[i].roomName +'">'+ data[i].roomName+'</option>');
});
},
complete: function(){
}
});
}
function District(sid){
$('#districtddl').empty();
$('#districtddl').append("<option>Loading...</option>");
$.ajax({
type:"POST",
url:"custom.php?sid="+sid,
contentType:"application/json; charset=utf-8",
dataType="json",
success: function(data){
$('#districtddl').empty();
$('#districtddl').append("<option value='0'> - </option>");
$.each(data,function(i,item){
$('#districtddl').append('<option value="'+ data[i].roomPrice +'">'+ data[i].roomPrice +'</option>');
});
},
complete: function(){
}
});
}
$(document).ready(function(){
State();
$("#stateddl").change(function(){
var roomName = $("#stateddl").val();
District(roomName);
});
});
</script>
</head>
<body>
<select name="stateddl" id="stateddl"></select> <select name="districtddl" id="districtddl"></select>
</body>
</html>
custom2.php
<?php
include("connection.php");
$sql=mysql_query("SELECT * FROM roomtype");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[] = array
(
'roomName' => $row['roomName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
custom.php
<?php
include("connection.php");
$sql=mysql_query("SELECT * FROM roomtype WHERE roomName='".$_GET["sid"]."'");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[] = array
(
'sid' => $row['roomName'],
'roomPrice' => $row['roomPrice']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
答案 0 :(得分:0)
问题在于以下功能块,
function District(sid){
...
$.ajax({
...
dataType="json",
...
});
}
请参阅AJAX请求的dataType
设置,错误的=
符号。它应该是dataType:"json"