Ajax函数封装与调用

来源:互联网 发布:中文域名不流行 编辑:程序博客网 时间:2024/06/05 14:42

Ajax函数封装与调用

1.  有四个参数传输的方式getpost,路径url,数据data,回调函数第四步

2.  function ajax(method,url,data,fnsuccess){

3.       //1号线:创建ajax对象

4.       var xhr;

5.       if(window.XMLHttpRequest){

6.        xhr=newXMLHttpRequest();

7.       }

8.       else{

9.        xhr=newActiveXObject('Microsoft.XMLHTTP');

10.      }

11.      //2号线:发送http请求(准备数据,真正的发送)

12.      if(method=='GET'&& data){

13.       //如果是get方式,并且有data:传数据到服务器

14.       url=url+'?'+data;

15.      }

16.      xhr.open(method,url,true);

17.      if(method=='GET'){

18.       xhr.send(null);

19.      }

20.      else{

21.       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

22.       xhr.send(data);

23.      }

24.      //4号线:拿到的数据返回给调用ajax函数的地方

25.      xhr.onreadystatechange=function(){

26.       if(xhr.readyState==4){

27.          if(xhr.status==200){

28.             if(fnsuccess){

29.                 fnsuccess(xhr.responseText);//注意这里只能接收字符串,jsonhtml数据。如果传过来的是xml数据格式,要换用responseXML属性

30.             }

31.            

32.          }

33.          else{

34.             alert('出差了,出错状态是:'+xhr.status);

35.          }

36.       }

37.      }

38. }

运用Ajax函数;

1.  <!DOCTYPE html>

2.  <html>

3.       <head>

4.        <meta charset="UTF-8">

5.        <title></title>

6.  调用函数;

7.        <script src="ajax.js" type="text/javascript" charset="utf-8"></script>

8.        <script type="text/javascript">

9.           window.onload=function(){

10.             var oBtn=document.getElementById('btn');

11.             触发的事件

12.             oBtn.onclick=function(){

13.                 填写参数

14.                 ajax('GET','aa.txt','',function(str){

15.                    第四步

16.                    console.log(str);

17.                 });

18.             }

19.          }

20.       </script>

21.      </head>

22.      <body>

23.       <input type="button" name="" id="btn" value="获取数据"/>

24.       <div></div>

25.      </body>

26. </html>