我如何在响应本机中通过axios.get在数组而不是字符串中获得响应?

时间:2019-04-11 11:09:36

标签: php react-native axios

我通过php代码连接到db,我编写了一些代码以在react native中使用axios.get获取数据。但是axios.get的响应是字符串而不是数组。

我尝试使用eval(response)和JSON.parse(response),但是无法将响应转换为数组。

这是我的React本机代码,它写在componentDidMount

const mobile = "0912111111";

const data = {

      mobile: mobile
   };
   var headers = {

        'Content-Type': 'application/json'
    }
    axios.get('http://192.168.1.3/Account/family_manage.php',{data:data}, 
    {headers:headers})
    .then((response) => {

   //how to convert response to array of array here
   console.log(eval(response).data);

  })
  .catch(function (error) {
    Alert.alert('error');
    console.log(error);
    });

这是我在php后端中的代码:

header("Access-Control-Allow-Origin: *");
include "connect.php";

$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$mobile=$obj['mobile'];

$sql = "SELECT box_name,num_box FROM family_box WHERE 
admin_mobile='$mobile'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_array($result)){

          $myarr[] =array('name'=> $row['box_name'],'num'=>$row['num_box']);
     }


    echo json_encode($myarr);
 } else {
      echo "0 results";
  }

 mysqli_close($conn);

如何获取数组响应数组以及如何在响应数据中访问“名称”或num? 谢谢

1 个答案:

答案 0 :(得分:1)

在轴上,您无需将数据转换为字符串化就可以自动完成,您可以像this.setState({response:response})这样直接使用 如果您想在屏幕上查看该数据以进行检查,也可以通过console.warn(response)

进行检查

这是我用于应用程序的示例

  async function getshoppinapi(link) {
      let responseJson = await axios.get(link,{ headers: {"Authorization" : `Bearer ${global.token}`} })
      //let responseJson = response;
      return responseJson;
}