兼容IE6的fetch polyfill

react社區起來後,不知足如今的AJAX方案,搞了一個fetch。fetch只有在一些很是新的瀏覽器才支持,而github上的fetch卻最多兼容到IE8,而且麻煩得要死,須要安裝一大堆polyfill才能運行起來。javascript

因而我搞了一個兼容IE6的polyfill。用法與原生的如出一轍。html

npm install fetch-polyfill2

固然想要在IE6運行起來,還須要Promise與JSON3。java

推薦使用性能最好的bluebird與JSON3react

$ npm install bluebird -- save
$ npm install json3 -- save

它內部是使用4種通訊手段與後端交換數據git

clipboard.png

HTML

fetch('/users.html')
  .then(function(response) {
    return response.text()
  }).then(function(body) {
    document.body.innerHTML = body
  })

JSON

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

Response metadata

fetch('/users.json').then(function(response) {
  console.log(response.headers.get('Content-Type'))
  console.log(response.headers.get('Date'))
  console.log(response.status)
  console.log(response.statusText)
})

Post form

var form = document.querySelector('form')

fetch('/users', {
  method: 'POST',
  body: new FormData(form)
})

Post JSON

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})

File upload

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

IE6-7 cors

fetch('/users', { //jsonp!!!
  credentials: 'include',
}).then(function(response){
   return response.json()
}).then(function(){

})

歡迎star與pull request https://github.com/RubyLouvre...github

相關文章
相關標籤/搜索