ajax生成下拉框
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD>
- <meta charset="gbk">
- <TITLE> Ajax </TITLE>
- <script language="javascript">
- var xmlHttp;
- function createXMLHttpRequest(){
- if(window.ActiveXObject){
- xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
- //xmlHttp=new XMLHttpRequest();
- }else{
- //xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
- xmlHttp=new XMLHttpRequest();
- }
- }
- function getCity(){
- createXMLHttpRequest();
- xmlHttp.open("POST","C:\\Users\\fzx\\Desktop\\data.xml");
- xmlHttp.onreadystatechange=getCityCallback;
- xmlHttp.send(null);
- }
- function getCityCallback(){
- if(xmlHttp.readyState==4){
- alert(xmlHttp.statusText);
- if(xmlHttp.status==200){
- alert("*************");
- var allerea=xmlHttp.responseXML.getElementsByTagName("allarea")[0].childNodes;
- alert(allerea);
- var select=document.getElementById("city");
- select.length=1;
- select.options[0].selected=true;
- for(var i=0;i++;i<allarea.length){
- var area=allarea[i];
- var option=document.createElement("option");
- var value=area.getElementsByTagName("value")[0].firstChild.nodeValue;
- var title=area.getElementsByTagName("title")[0].firstChid.nodeValue;
- option.setAttribute("value",value);
- option.appendChild(document.createTextNode(title));
- select.appendChild(option);
- }
- }
- }
- }
- </script>
- </HEAD>
- <BODY onload="getCity()">
- <form action="" method="post">
- <select id="city">
- <option value="">--请选择--</option>
- </select>
- </form>
- </BODY>
- </HTML>
2、以下为xml数据:
- <?xml version="1.0" encoding="utf-8">
- <allarea>
- <area>
- <value>1</value>
- <title>云浮</title>
- </area>
- <area>
- <value>2</value>
- <title>肇庆</title>
- </area>
- <area>
- <value>3</value>
- <title>中山</title>
- </area>
- <area>
- <value>4</value>
- <title>广州</title>
- </area>
- </allarea>
1)把代码放到网站测试:url="http://localhost/....."
2) 离线环境下,用同步试试
- function getCity(){
- createXMLHttpRequest();
- xmlHttp.open("GET","C:\\Users\\fzx\\Desktop\\data.xml",false);
- ////xmlHttp.onreadystatechange=getCityCallback;//注意,同步下不能使用
- xmlHttp.send(null);
- //这里直接取数据
- var ret=responseXML
- }
2、如果你使用POST,要根据数据传输类型加头信息:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
或 xmlHttp.setRequestHeader("Content-Type","text/XML");之类的