php:
<?php
//向客户端返回所有的商品类别,以JSON字符串格式
header('Content-Type: application/json');
$db = [
['tno'=>101, 'tname'=>'电脑'],
['tno'=>102, 'tname'=>'数码相机'],
['tno'=>103, 'tname'=>'手机'],
['tno'=>104, 'tname'=>'洗衣机']
];
$jsonString = json_encode($db);
echo $jsonString;
?>
html:
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta charset="utf-8" />
</head>
<body>
<h1>使用AJAX技术实现“动态页面静态化”</h1>
<select id="type">
<option value="0">—请选择产品类别—</option>
</select>
<select id="producer">
<option value="0">—请选择生产厂家—</option>
</select>
<script>
var selectType = document.getElementById('type');
var selectProducer = document.getElementById('producer');
//页面加载完成后发起异步请求,获取产品类别列表
window.onload = function(){
//1
var xhr = new XMLHttpRequest();
//2
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status===200){
doResponse(xhr.responseText);
}else{
console.log('失败的响应');
}
}
}
//3
xhr.open('GET','1-gettype.php', true);
//4
xhr.send(null);
}
function doResponse(txt){
console.log('开始处理响应数据:');
//console.log(typeof txt);
//console.log(txt);
//把服务器端返回JSON字符串解析为JS对象
var obj = JSON.parse(txt);
//console.log(typeof obj);
console.log(obj);
for(var i=0; i<obj.length; i++){
var type = obj[i];
selectType.innerHTML += '<option value="'+type.tno+'">'+type.tname+'</option>';
}
}
selectType.onchange = function(){
console.log('用户的选项发生改变了:');
var tno = this.value;
console.log(tno);
//发起异步的请求,根据tno获取对应的厂家
//1
//2
//3
//4
}
</script>
</body>
</html>