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" οnclick="showInfo()">
61 <div id="infoDiv"></div>
62 </body>
63 </html>

initAjax函数实现了对浏览器的兼容(IE5,6), 不过现在ActiveX技术早已过时, 被浏览器默认禁用.

showInfo函数中将xhrStateChange函数绑定到onreadystatechange事件, 注意这种绑定方式不支持传参(只写函数名不能加括号)!!!而且这句代码写在函数外也是可以的.结果如下

 

第49行如果把innerHTML改为innerText, 则将不考虑xml文件中的标签, 内容原样显示, 如下

另外, xhr除了responseText属性, 还有一个属性:responseXml.

附readyState的各状态

 

转载于:https://www.cnblogs.com/wincent98/p/9953257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值