dongquming3255 2018-11-13 17:54
浏览 115

如何将数据从React Native应用程序传递到PHP脚本?

I'm using this code to pass the userName variable...

return fetch('http://creat1vedesign.com/userTabs4.php', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
            'Content-Type': 'application/json',
  },
}, {
  body: JSON.stringify({
      userName: 'carolf'
  }),

...to this php script...

<?php
include 'DBConfig.php';
$con = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
    $json = file_get_contents('php://input');
    $obj = json_decode($json,true);
    $userName = $obj['userName'];
$sql = "select * from Users where userName = '$userName'";
if ($result = mysqli_query($con,$sql)) { 
 while($row[] = $result->fetch_assoc()) {
    $tem = $row;
    $json = json_encode($tem);
 }
} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?>

...to retrieve data for a specific criteria. But either the React Native is not sending the data or the php script is not receiving it or the syntax is incorrect or I'm doing something else wrong :(

Any thoughts?

  • 写回答

1条回答 默认 最新

  • douyuan3842 2018-12-18 23:09
    关注

    You can pass the parameters to the PHP script in the fetch URL by adding them after a '?' like this:

    fetch("http://creat1vedesign.com/userTabs4.php?userName=carolf",{
            method:'POST',
            headers:{
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
          })
    
          .then( (response) => {
                return response.json() })   
                    .then( (json) => {
                        console.log(json)
                    });
    

    Just make sure to include a $_GET in your php script:

    <?php
    
    $userName= $_GET["userName"];
    
    include 'DBConfig.php';
    $con = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
    $json = file_get_contents('php://input');
    $obj = json_decode($json,true);
    
    $sql = "select * from Users where userName = '$userName'";
    if ($result = mysqli_query($con,$sql)) { 
     while($row[] = $result->fetch_assoc()) {
        $tem = $row;
        $json = json_encode($tem);
     }
    } else {
     echo "No Results Found.";
    }
     echo $json;
    $conn->close();
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。