React-Native Fetch方法发送网络请求
先贴一个官方文档。 fetch('https://mywebsite.com/endpoint/',{ method: 'POST',headers: { 'Accept': 'application/json','Content-Type': 'application/json',},body: JSON.stringify({ firstParam: 'yourValue',secondParam: 'yourOtherValue',}) }) 一开始我就是单纯的这么写的,愉快的把URL替换掉,把参数替换掉,然后。。。 $json = json_decode(file_get_contents('php://input'),true); var_dump($json['firstParam']); 但是这样会影响到现有的web应用,所以又继续查资料,发现可以改成下边这样的方法。 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'];接收了。 文章首发在:React-Native Fetch方法发送网络请求 Sending data as key-value pair using fetch polyfill in react-native (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |