ajax和fetch的3大缺陷,fetch与ajax的区别

一. Fetch 是 window 下面的一个方法Fetch 写法: 1

2

3

4

5

6

7

8

9

10

11

12

fetch('url',{

methods:'get'

})

.then(function(res){

return

})

.then(function(){

return // 执行成功第二步

})

.catch(function(err){

//异常报错

})

Fetch 常见处理:

HTML

1

2

3

4

5

6

7

fetch('/user.html')

.then(function(res){

return res.text();

})

.then(function(body){

document.body.innerHTML = body;

})

JSON

1

2

3

4

5

6

7

8

fetch('/users.json')

.then(function(response){

return response.json()

}).then(function(json){

console.log('parsed json', json)

}).catch(function(ex){

console.log('parsing failed', ex)

})

Post form

1

2

3

4

5

6

7

8

9

10

11

12

13

var form = document.querySelector('form');

fetch('/user',{

method:'POST',

headers:{

'Content-Type':'application/json'

},

body:JSON.stringify({

name:'fetch',

login:'fetct'

})

})

File upload

1

2

3

4

5

6

7

8

9

10

var input = document.querySelector('input[type="file"]')

var data = new FormData()

data.append('file', input.files[0])

data.append('user', 'hubot')

fetch('/avatars', {

method: 'POST',

body: data

})

….

等等

二.Ajax定义:AJAX全称“Asynchronous JavaScript and XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。本质是使用XMLHttpRequest 来请求数据。举个栗子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

function (options){

options = options || {};

options.type = (options.type || "get").topUpperCase();

options.dataType = options.dataType || "json";

var params = formatParams(options.data);

if(window.XMLHttpRequest){//创建xhr

var xhr = new XMLHttpRequest();

}else{

var xhr = ActiveXObject('Microsoft.XMLHTTP');

}

}

//接收

xhr.onreadystatechange=function(){

if(xhr,readyState == 4){

var status = xhr.status;

if(status >= 200 && options.success(xhr.responseText,xhr.responseXML)){

options.success && options.success(xhr.responseText,xhr.responseXML);

}else{

options.fail && options.fail(status);

}

}

}

//连接发送

if(options.type =="GET"){

xhr.open("GET",option.url+"?"+params,true);

xhr.send(null);

}else if(options.type =="POST"){

xhr.open("POST",options.url,true);

xhr.setRequestHeader("Content-Type","application/x-www-form-urllencoded");

xhr.send(params);

}

//格式化参数

function formatParams(data){

var arr=[];

for (var name in data) {

arr.push(encodeURLCompontent(name)+"="+encodeURLCompontent(data[name]));

}

arr.push(("v="+Math.random()).replace(".",""));

return arr.join("&");

}

ajax({

url: "./TestXHR.aspx", //请求地址

type: "POST", //请求方式

data: { name: "super", age: 20 }, //请求参数

dataType: "json",

success: function (response, xml){

// 此处放成功后执行的代码

},

fail: function (status){

// 此处放失败后执行的代码

}

});

总结

1.从 fetch() 返回的 Promise 将不会拒绝 HTTP 错误状态, 即使响应是一个 HTTP 404 或 500。相反,它会正常解决 (其中 ok 状态设置为 false), 并且仅在网络故障时或任何阻止请求完成时,它才会拒绝

2.默认情况下, 如果站点依赖维护用户会话(发送 cookie,必须设置 credentials init 选项), fetch 则不会发送或接收来自服务器的任何 cookie,导致未经身份 验证的请求。

3.在语法上 fetch 比 ajax 简洁了许多。

4.兼容上目前 fetch 兼容不是太好 使用时需要引入 polyfill :GitHub - github/fetch: A window.fetch JavaScript polyfill.

在默认情况下 fetch 不会接受或者发送 cookies,如果需要只能手动设置 credentials: ‘include’

1

2

3

4

5

6

fetct('/api',{

credentials: 'include'

})

.then(function(res){

return // ...

})

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值