如何封装一个Ajax函数

如何封装Ajax函数

一个Ajax函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// 一个Ajax函数

var xhr = null;

if(window.XMLHttpRequest){

   xhr = new XMLHttpRequest;

}else{

   xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.open("GET","https://jsonplaceholder.typicode.com/users");

xhr.send(null);

xhr.onreadystatechange = function(){

   if(this.readyState === 4){

        console.log(xhr.responseText)

    }

}

封装自己的 Ajax 函数

参数1:{string} 请求方法--method
参数2:{string} 请求地址--url
参数3:{object} 请求参数--params
参数4:{function} 请求完成后,执行的回调函数--done

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

function ajax(method,url,params,done){

//  统一将method方法中的字母转成大写,后面判断GET方法时 就简单点

  method = method.toUpperCase();

  //IE6的兼容

  var xhr = window.XMLHttpRequest

   ? new XMLHttpRequest()

   : new ActiveXObject("Microsoft.XMLHTTP");

 

  //创建打开一个连接 open

              

  //将对象格式的参数转为urlencoded模式

  //新建一个数组,使用for循环,将对象格式的参数,

  //以(id = 1)的形式,每一个键值对用 & 符号连接

 var pairs = [];

 for(var k in params){

     pairs.push(k + "=" + params[k]);

  }

  var str = pairs.join("&");      

  //判断是否是get方法 , get方法的话,需要更改url的值

 if(method == "GET"){

       url += "?" + str;

  }

              

//创建打开一个连接

 xhr.open(method,url);

 

var data = null;

if(method == "POST"){

    //post方法 还需要设置请求头、请求体

    xhr.setRequestHeader("Content-Type",

    "application/x-www-form-urlencoded");

    data = str;

                  

}

xhr.send(data);

 

 //执行回调函数

xhr.onreadystatechange = function(){

   if(this.readyState == 4) {

       done(JSON.parse(this.responseText));

   }return;

   // 执行外部传进来的回调函数即可

   // 需要用到响应体

   }

 

//调用函数

//get方法

//  ajax("GET","http://localhost:3000/users",

//     {"id":1},

//     function(data){

//         console.log(data);

//  });

 

//post方法    

ajax("POST", "http://localhost:3000/users",

 { "name": "lucky","class":2,"age":20 },

 function (data) {

     console.log(data);

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苍狼_2001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值