ES6 fetch函數與後臺交互實現

最近在學習react-native,遇到調用後端接口的問題.看了看官方文檔,推薦使用es6的fetch來與後端進行交互,在網上找了一些資料.在這裏整理,方便之後查詢.php

1.RN官方文檔中,可以使用XMLHttpRequest前端

var request = new XMLHttpRequest();
request.onreadystatechange = (e) = >{
  if (request.readyState !== 4) {
    return;
  }
  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};
request.open('GET', 'https://mywebsite.com/endpoint.php');
request.send();

這是http的原生方法,這裏不作多的介紹.react

2.RN官方文檔中,推薦使用fetches6

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
}).then(function(res) {  console.log(res)
})

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力,羣內有大量PDF可供自取,更有乾貨實戰項目視頻進羣免費領取。web

body中的數據就是咱們須要向服務器提交的數據,好比用戶名,密碼等;若是上述body中的數據提交失敗,那麼你可能須要把數據轉換成以下的表單提交的格式:ajax

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: 'key1=value1&key2=value2'
}).then(function(res) {
 
    console.log(res)
})

這樣能夠獲取純文本的返回數據. 若是你須要返回json格式的數據:json

fetch('https://mywebsite.com/endpoint/').then(function(res) {
 
  if (res.ok) {
 
    res.json().then(function(obj) {
 
      // 這樣數據就轉換成json格式的了
 
    })
 
  }
 
}, function(ex) {
  console.log(ex)
})

fetch模擬表單提交:後端

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力,羣內有大量PDF可供自取,更有乾貨實戰項目視頻進羣免費領取。react-native

fetch('doAct.action', { 
 
  method: 'post', 
 
  headers: { 
 
   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
 
  }, 
 
  body: 'foo=bar&lorem=ipsum'
 
 })
 
 .then(json) 
 
 .then(function (data) { 
 
  console.log('Request succeeded with JSON response', data); 
 
 }) 
 
 .catch(function (error) { 
 
  console.log('Request failed', error); 
 
 });

不過不管是ajax仍是fetch,都是對http進行了一次封裝,你們各取所好吧.服務器

相關文章
相關標籤/搜索