Ajax---001
- 创建xmlhttp对象
1 function ajaxFunction(){ 2 var xmlHttp; 3 try { 4 //firefox,opera,safari 5 xmlHttp = new XMLHttpRequest(); 6 } catch (e) { 7 try { 8 //Internet explore 9 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 10 } catch (e) { 11 try { 12 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 13 } catch (e) { 14 } 15 16 } 17 } 18 return xmlHttp; 19 }
- 使用GET或POST方式不带参数时的访问方式
1 function func02(){ 2 var request = ajaxFunction(); 3 request.open("GET","servletURL",true); 4 //request.open("POST","servletURL",true); 5 request.send(); 6 }
- 使用POST方式带数据的访问方式
1 function func01(){ 2 //创建ajax对象 3 var myrequest = ajaxFunction(); 4 5 //发送请求 6 myrequest.open("POST","DemoServlet01",true); 7 myrequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 8 myrequest.onreadystatechange = function(){ 9 if(myrequest.readyState == 4 && myrequest.status == 200){ 10 alert(myrequest.responseText); 11 } 12 13 } 14 myrequest.send("name=aliy&age=19"); 15 }
- 使用GET方式请求时可能得到的是缓存的结果,可以通过向url中添加唯一的uid来解决
1 xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true); 2 xmlhttp.send();