1. 程式人生 > >fetch和XMLHttpRequest

fetch和XMLHttpRequest

eth 寫上 set clas 使用 發送 .org 用戶 cti

除了XMLHttpRequest對象來獲取後臺的數據之外,還可以使用一種更優的解決方案fetch

到現在為止,fetch的支持性還不是很好,但是在谷歌瀏覽器中已經支持了fetch。fetch掛在在BOM中,可以直接在谷歌瀏覽器中使用。

查看fetch的支持情況:fetch的支持情況

當然,如果不支持fetch也沒有問題,可以使用第三方的ployfill來實現只會fetch:whatwg-fetch

下面我們來寫第一個fetch獲取後端數據的例子:

// 通過fetch獲取百度的錯誤提示頁面
fetch(‘https://www.baidu.com/search/error.html‘) // 返回一個Promise對象
  .then((res)=>{
    return res.text() // res.text()是一個Promise對象
  })
  .then((res)=>{
    console.log(res) 
// 通過fetch獲取百度的錯誤提示頁面
fetch(‘https://www.baidu.com/rec?platform=wise&ms=1&rset=rcmd&word=123&qid=11327900426705455986&rq=123&from=844b&baiduid=A1D0B88941B30028C375C79CE5AC2E5E%3AFG%3D1&tn=&clientWidth=375&t=1506826017369&r=8255‘, { // 在URL中寫上傳遞的參數
    method: ‘GET‘,
    headers: new Headers({
      ‘Accept‘: ‘application/json‘ // 通過頭指定,獲取的數據類型是JSON
    })
  })
  .then((res)=>{
    return res.json() // 返回一個Promise,可以解析成JSON
  })
  .then((res)=>{
    console.log(res) // 獲取JSON數據
  })

強制帶Cookie

默認情況下, fetch 不會從服務端發送或接收任何 cookies, 如果站點依賴於維護一個用戶會話,則導致未經認證的請求(要發送 cookies,必須發送憑據頭).

// 通過fetch獲取百度的錯誤提示頁面
fetch(‘https://www.baidu.com/search/error.html‘, {
    method: ‘GET‘,
    credentials: ‘include‘ // 強制加入憑據頭
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

fetch和XMLHttpRequest