替代传统XMLHttpRequest的fetch方法实现ajax

FETCH API提供了一个JavaScript接口,用于访问和操作HTTP管道的某些部分,例如请求和响应。它还提供了一种全局fetch()方法,它提供了一种简单、逻辑的方法来跨网络异步地获取资源。

与jquery.ajax()方法不同的两点:

1、即使响应返回404、500等错误,它也不会出错,只会返回一个网络错误。

2、默认情况下,fetch不会发送和返回cookie。但可以通过初始化参数添加这项功能,var init = {credentials: 'include' // 请求带上cookies}。这点在需要权限验证的操作时一定要注意。

基础用法:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Supplying request options

// Example POST method implementation:


postData(`http://example.com/answer`, {answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error));

const postData = (url = ``, data = {}) => {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()) // parses response to JSON
    .catch(error => console.error(`Fetch Error =\n`, error));
};

 如果需要发送包含凭证的需求

fetch('https://example.com', {
  credentials: 'include'  
})
credentials: 'omit'

 返回json类型的数据

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

浏览器支持

桌面:Chrome 42以上,Edge 14以上,IE不支持,Firefox 52以上全支持,Opera 29以上,Safari (WebKit) 10.1以上。

移动:Android Webview 42以上,Chrome for Android 42以上,Firefox Mobile (Gecko) 支持,Safari Mobile 10.1以上,IE Phone不支持,Opera Mobile 暂不知道

转载于:https://my.oschina.net/u/3007124/blog/1839516

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值