业务需求:
第一步:加载商品类别,点“加载种类” 按钮
第二步:选择商品种类显示该类别的所有商品,也是异步请求:
这时要注意xmlHttpRequest的创建及 onreadystatechange 回调函数的设置
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript">
<script type="text/javascript">
var xmlhttp;
function createXmlHttp(){
if(window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else{
xmlhttp=new XmlHttpRequest();
}
}
//第一次异步请求
function loadCategory(){
createXmlHttp();
xmlhttp.onreadystatechange=getCategory;
xmlhttp.open("GET","show!findAllCategories.action",true);
xmlhttp.send();
}
function getCategory(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var sel=document.getElementById("div1");
sel.innerHTML=xmlhttp.responseText;
}
}
}
//第二次异步请求
function getData(){
createXmlHttp();//另一个xmlhtpp对象,必须重新创建,否则和第一个相同
xmlhttp.onreadystatechange=getProduct;
document.getElementById("div2").innerHTML="";
xmlhttp.open("GET","showPro!findProByCategoryId.action?id="+document.getElementById("dept").value,true);
xmlhttp.send();
}
function getProduct(){
if(xmlhttp.readystate==4){
if(xmlhttp.status==200){
var sel1=document.getElementById("div2");
sel1.innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<div id="div1">
<input type="button" value="加载种类" οnclick="loadCategory()">
</div>
<div id="div2"></div>
</body>
</html>