ajax实现的二级联动_读取的是json格式数据

jsp页面

<body>
<div>
<select id="collTag" onchange="selectChange(this.options[this.options.selectedindex].value)">
<option value="0">====请选择====</option>
</select>
<select id="optTag">
<option value="0">====请选择====</option>
</select>
</div>
</body>

js代码

<script>
/**
* 项目思路:在页面加载的时候初始化第一个选项,
2:当第一个下拉列表发生改变是触动change函数来改变第二个下拉列表的内容
2.1:读取xml文件内容
2.2:判断用户选中的option的value值
2.3:遍历xml文件找到与用户对应的值,添加到第二个下拉列表项中

*/
function createXmlHttpRequest(){
var xmlHttp ;
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
return xmlHttp;
}

//ajax的回调函数
function callBack(){
if(this.readyState == 4 && this.status == 200){
var resultJson = eval('('+this.responseText+')');
//alert(resultJson.length);
for(var i=0;i<resultJson.length;i++){
//alert(resultJson[i].name);//软件学院,计算机学院
//得到页面元素
var selTag = document.getElementById("collTag");
var option = document.createElement("option");
option.text = resultJson[i].name;
option.value = resultJson[i].name;
selTag.appendChild(option);
}

}
}

window.onload = function(){
//ajax四步
var xmlHttp = createXmlHttpRequest();
//alert(xmlHttp);
//打开与服务器的连接
xmlHttp.open("GET","yxb.json",true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = callBack;


}

function selectChange(value){
//得到页面选择的value值 this.options[this.options.selectedindex].value
//alert(value);//选择的option的value值
//依然是ajax的四步;
//之后从页面获取
var xmlHttp = createXmlHttpRequest( );
//alert(xmlHttp);
//打开与服务器的连接
xmlHttp.open("GET",true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function (){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var resultJson = eval('('+xmlHttp.responseText+')');
//alert(resultJson.length);
for(var i=0;i<resultJson.length;i++){
//alert(resultJson[i].name);//软件学院,计算机学院
//得到页面元素
if(resultJson[i].name == value){
var optTag = document.getElementById("optTag");
optTag.options.length = 0;
for(var j=0;j<resultJson[i].children.length;j++){
var option = document.createElement("option");
option.text = resultJson[i].children[j].name;
option.value = resultJson[i].children[j].name;
optTag.appendChild(option);
//alert("hello:\t"+resultJson[i].children[j].name);
}
}
}
}
};

}
</script>

college.json

[ { "value":1,"name":"软件学院","children": [ { "value":1,"name":"软件工程",},{ "value":2,"name":"网络工程",} ] },"name":"计算机学院","name":"数据结构","name":"操作系统",} ] } ]

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...