dsfasdfsda234234 2017-11-10 06:09
浏览 298
已采纳

React本机http获取请求无效

I'm new to react native trying to do the http request using fetch method (also tried axios). I'm using PHP as backend. What I'm trying is to print the JSON object returned from server in react native.

I'm sure that the response is returning from server cause I printed the result and it is a JSON array. But when I consoled the responseData using Chrome dev tools I got this []. I don't know where the mistake is.

index.js

    componentDidMount(){

        fetch('http://xxxxxxxxxx/result.php', {
            method: 'GET',
        }).then(response =>response.json())
          .then((responseData) =>
          {
              console.log(responseData);
              this.setState({
                  user: (responseData.name),
                  loaded:true,
              })

        });         
}
    render(){
        return(
        <Card>  
  <CardTitle style={styles.containerStyle} title={this.state.user} />
</Card>
        );
    }
}

Also my php is script is as follows

result.php

<?php
include 'db.php';
$check_json = file_get_contents('php://input');

$obj1= json_decode($check_json);
$uid =$obj1->{'uuid'};
$blood = $obj1->{'bloodgroup'};
$loc = $obj1->{'place'};
$prep =$mysqli->prepare("select token,name,uuid from signup where location 
like '".$loc."%' and bloodgroup= ?");
$prep->bind_param("s",$blood);
$prep->execute();
$result= $prep->get_result();
$payload= array();
while($row= $result->fetch_array(MYSQL_ASSOC)){
   $payload[]= array('name' =>$row['name']
                    'uuid' =>$row['name']);
}
$obj2 =json_encode($payload);
echo $obj2;
?>

and the response from server is

 [{"name":"angel","uuid":"b4b8a266-60cf-4e30-a778-596316d1a4a2"}]
  • 写回答

3条回答 默认 最新

  • douzhi4991 2017-11-10 06:29
    关注

    Try using axios. You can check the docs here After you have done npm install axios and imported axios into your component you can try:

    componentDidMount(){
    axios
      .get('https://www.your-url.com/path-to-your-php-api')
      .then(({ data })=> {
        this.setState({ 
          user: data.name
        });
      })
      .catch((err)=> {})
    }
    

    if you still have problems, post the url that returns JSON so I can take a look.

    Check your PHP API, if the object is returning empty, make sure to encode json. Here is an example you can try

    $myObj->name = "Michel Arteta";
    $myObj->age = 30;
    $myObj->city = "New York";
    
    $myJSON = json_encode($myObj);
    
    echo $myJSON;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器