加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:51:48 所属栏目:百科 来源:网络整理
导读: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代码

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":"操作系统",} ] } ]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读