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

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

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

一、即便响应返回40四、500等错误,它也不会出错,只会返回一个网络错误。json

二、默认状况下,fetch不会发送和返回cookie。但能够经过初始化参数添加这项功能,var init = {credentials: 'include' // 请求带上cookies}。这点在须要权限验证的操做时必定要注意。浏览器

基础用法:cookie

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));
};

 若是须要发送包含凭证的需求app

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

 返回json类型的数据cors

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以上。post

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

相关文章
相关标签/搜索