一、RN官方文檔,能夠使用XMLHttpRequestjavascript
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原生的方法,不作過多介紹。
二、RN官方文檔中,推薦使用fetchphp
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) })
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) })這
這樣能夠獲取純文本的返回數據。java
若是你須要返回json格式的數據:web
fetch('https://mywebsite.com/endpoint/').then(function(res) { if (res.ok) { res.json().then(function(obj) { // 這樣數據就轉換成json格式的了 }) } }, function(ex) { console.log(ex) })
fetch模擬表單提交ajax
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進行了一次封裝,不過是各取所需。json
參考文檔:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch服務器