ES6 fetch函式與後臺互動實現
阿新 • • 發佈:2018-12-29
最近在學習react-native,遇到呼叫後端介面的問題.看了看官方文件,推薦使用es6的fetch來與後端進行互動,在網上找了一些資料.在這裡整理,方便以後查詢.
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的原生方法,這裡不做多的介紹.
2.RN官方文件中,推薦使用fetch
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可供自取,更有乾貨實戰專案視訊進群免費領取。
body中的資料就是我們需要向伺服器提交的資料,比如使用者名稱,密碼等;如果上述body中的資料提交失敗,那麼你可能需要把資料轉換成如下的表單提交的格式:
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格式的資料:
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可供自取,更有乾貨實戰專案視訊進群免費領取。
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進行了一次封裝,大家各取所好吧.