替代傳統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 暫不知道

相關文章
相關標籤/搜索