Ajax基本写法
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>Insert title here</title>
6 <script>
7 var xhr=initAjax();
8 function initAjax()
9 {
10 if(window.XMLHttpRequest)
11 {
12 return new XMLHttpRequest();
13 }
14 else if(window.ActiveXObject)
15 {
16 try
17 {
18 return new ActiveXObject("Msxml2.XMLHttp");
19 }
20 catch(e)
21 {
22 try
23 {
24 return new ActiveXObject("Microsoft.XMLHttp");
25 }
26 catch(e)
27 {
28 //return undefined
29 alert("Your browser doesn't support AJAX!");
30 }
31 }
32 }
33 }
34 function showInfo()
35 {
36 //var xhr=new ActiveXObject("Msxml2.XMLHttp");
37 if(xhr!=null)
38 {
39 xhr.onreadystatechange=xhrStateChange;
40 xhr.open("GET","info.xml",true);
41 xhr.send(null);
42 }
43
44 }
45 function xhrStateChange()
46 {
47 if(xhr.readyState==4)
48 {
49 document.getElementById("infoDiv").innerHTML=xhr.responseText;
50 }
51 else if(xhr.readyState==3)
52 {
53 document.getElementById("infoDiv").innerHTML="Loading...";
54 }
55
56 }
57 </script>
58 </head>
59 <body>
60 <input type="button" value="click me" onclick="showInfo()">
61 <div id="infoDiv"></div>
62 </body>
63 </html>
initAjax函數(shù)實(shí)現(xiàn)了對(duì)瀏覽器的兼容(IE5,6), 不過現(xiàn)在ActiveX技術(shù)早已過時(shí), 被瀏覽器默認(rèn)禁用.
showInfo函數(shù)中將xhrStateChange函數(shù)綁定到onreadystatechange事件, 注意這種綁定方式不支持傳參(只寫函數(shù)名不能加括號(hào))!!!而且這句代碼寫在函數(shù)外也是可以的.結(jié)果如下
第49行如果把innerHTML改為innerText, 則將不考慮xml文件中的標(biāo)簽, 內(nèi)容原樣顯示, 如下
另外, xhr除了responseText屬性, 還有一個(gè)屬性:responseXml.
附readyState的各狀態(tài)
總結(jié)
- 上一篇: 我的自学之路:java学习路线图分享
- 下一篇: Windows2008安装组件命令行工具