先貼一個官方文檔。
Networkphp
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'yourOtherValue', }) })
一開始我就是單純的這麼寫的,愉快的把URL替換掉,把參數替換掉,而後。。。
我愉快的敲下 var_dump($_POST['firstParam'])
的時候,後臺沒接到任何東西,後來在stackoverflow上看到回答,說之因此接收不到,是由於這不屬於form data,想要這麼寫,須要在接收前添加 file_get_contents('php://input')
,而後果真就能夠了。html
$json = json_decode(file_get_contents('php://input'), true); var_dump($json['firstParam']);
可是這樣會影響到現有的web應用,因此又繼續查資料,發現能夠改爲下邊這樣的方法。react
function toQueryString(obj) { return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.sort().map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; }
fetch(url, { method: 'post', body: toQueryString({ 'firstParam': 'yourValue', 'secondParam':'yourOtherValue' }) })
這樣,在後臺就能夠正常的用$_POST['firstParam'];接收了。git
文章首發在:React-Native Fetch方法發送網絡請求github
Sending data as key-value pair using fetch polyfill in react-native
How can I use react-native with php with fetch return data is always nullweb