您的位置:首页 > Web前端 > JavaScript

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

2015-09-14 22:22 901 查看
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","yxb.json",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":"网络工程",

}

]

},

{

"value":2,

"name":"计算机学院",

"children":

[

{

"value":1,

"name":"数据结构",

},

{

"value":2,

"name":"操作系统",

}

]

}

]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: