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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?