一个最重要的文件,ajax.js:
function send_request(callback, urladdress, isReturnData){ var xmlhttp = getXMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4) {//readystate 为4即数据传输结束 try{ if(xmlhttp.status == 200){ if(isReturnData && isReturnData==true){ callback(xmlhttp.responseText); } }else{ callback("抱歉,没找到此页面:"+ urladdress +""); } } catch(e){ callback("抱歉,发送请求失败,请重试 " + e); } } } xmlhttp.open("GET", urladdress, true); xmlhttp.send(null); } function getXMLHttpRequest() { var xmlhttp; if (window.XMLHttpRequest) { try { xmlhttp = new XMLHttpRequest(); xmlhttp.overrideMimeType("text/html;charset=UTF-8");//设定以UTF-8编码识别数据 } catch (e) {} } else if (window.ActiveXObject) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHttp"); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml3.XMLHttp"); } catch (e) {} } } } return xmlhttp; }
//根据所选一级栏目动态改变所对应的二级栏目 function changSubitem(id) { var schoolItemid = get("school_" + id);//考区;很明确知道选择了这一个;直接使用getById获得 var url="share_hall!searchRoomsBySiteId.action?siteId="+schoolItemid.options[schoolItemid.selectedIndex].value; var rooms = document.getElementsByName("rooms_"+id); send_request(function(datas){ var str = eval(datas);//这个函数太牛B了,将这种格式的字符串解析成对象:"[["1","a"],["2","b"]]" for(var m=0;m<rooms.length;m++){//一共有六个联动单元 for ( var i = 0; i < datas.length; i++) { //remove option;一定要逆着减,否则会出错 for ( var x = rooms[m].options.length - 1; x >= 0;x--) { rooms[m].options.remove(x); } //add option for ( var x = 0; x < str.length; x++) { if(x==0){ rooms[m].options.add(new Option("请选择", "-1"));//为了让用户必须去触发onchange事件,所以加这个,一般不加,特殊处理 } var id = str[x][0]; var name = str[x][1]; rooms[m].options.add(new Option(name, id)); } } } },url,true); }