index.php页面程序:
<?php
header("Content-type: text/html; charset=gb2312");
$mypdo=new pdo("mysql:host=localhost;dbname=news","root","");
$sql="selects * from newstype";
$mypdo->query("set names gb2312");
$stmt=$mypdo->query($sql);
$rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<script src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(function(){
$("#menu1").change(function(){
$.getJSON("view.php",{index:$(this).val()},function(data){
var xs="";
var xx="";
for(var i=0;i<=data.length;i++){
xx+="<option value='"+data[i].id+"'>"+data[i].shi+"</option>";
//xx+=data[i].id+data[i].shi;
$("#shi").html(xx);
}
});
})
$("#menu1").change();
})
</script>
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="120">
<select id="menu1">
<?php foreach($rows as $rs){?>
<option value="<?php echo $rs['typeid'] ?>"><?php echo $rs['typename'] ?></option>
<?php } ?>
</select></td>
<td width="120"><select id="shi"><option>未选择</option></select></td>
<td> </td>
</tr>
</table>
view.php提供json格式数据:
<?php
header("Content-type: text/html; charset=gb2312");
if(!isset($_GET['index'])){
$tid=3;
}
else{
$tid=$_GET['index'];
}
$mypdo=new pdo("mysql:host=localhost;dbname=news","root","");
$sql="selects * from detailtype where typeid=$tid";
$mypdo->query("set names gb2312");
$stmt=$mypdo->query($sql);
$rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
$JSON_text="[";
$s=count($rows);
$i=1;
foreach($rows as $rs){
$JSON_text.='{"id":'.$rs['detailid'].',"shi":"'.$rs['detailname'].'"}';
if($i<$s){
$JSON_text=$JSON_text.",";
}
$i=$i+1;
}
$JSON_text.="]";
echo $JSON_text;
?>