首页 > 解决方案 > 在 react native 中发送和获取 JSON 数据 [JSON 解析错误]

问题描述

我有 2 个屏幕;[第一个屏幕 - 在这里用户输入手机号码] 这个手机号码应该传递给 JSON 并验证这个手机号码是否存在,如果手机号码存在,那么它会响应一些数据。此响应应传递到下一个屏幕。

这是我的第一个屏幕代码[用户输入数据的地方]-

class Register extends React.Component {
constructor(props) { 
    super(props) 
    this.state = {

    abc: ''
    } 
  }

  UserLoginFunction = () =>{

 const { abc } = this.state;

fetch('http://demo.weybee.in/react/User_Login.php', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({

  mobileno: abc,

      })

}).then((response) => response.json())
      .then((responseJson) => {
        // If server response message same as Data Matched
       if(responseJson != 'Enter valid phone number' )
        {   

            console.log(responseJson[0]);
            console.log(responseJson[1]);
            console.log(responseJson[2]);
            console.log(responseJson[3]);
            //Then open Profile activity and send user email to profile activity.
            this.refs.toast.show('Login successful', 500, () => {
            const { navigation } = this.props;

            const { abc }  = this.state ;

            navigation.navigate("Profile",
              {
                mobileno : abc, 
                myJSON: responseJson[0]+ " " +responseJson[1],
                myJSON2: responseJson[2],
                myJSON3: responseJson[3], },
              );
    });
        }
        else{

          Alert.alert(responseJson);
        }

      }).catch((error) => {
        console.error(error);
      });

  }
  render() {

    return (
<Block width={width * 0.8} style={{ marginBottom: 20, marginTop: 20 }}>
                      <Input
                        style={{borderRadius:50, borderWidth:5}}
                        onChangeText={abc => this.setState({abc})}
                        borderless
                        placeholder="Enter Mobile number"
                        keyboardType={'phone-pad'}
                        iconContent={
                          <Icon
                            size={16}
                            color={argonTheme.COLORS.ICON}
                            name="nav-right"
                            family="ArgonExtra"
                            style={styles.inputIcons}
                          />
                        }
                      />
                    </Block>

                    <Block middle>
                      <Button color="primary" style={styles.createButton} 
                       onPress={this.UserLoginFunction}>
                        <Text bold size={14} color={argonTheme.COLORS.WHITE}>
                          Log In
                        </Text>
                      </Button>
                      <Toast ref="toast"
                      style={{backgroundColor:'#131313'}}
                      textStyle={{color:'white',fontWeight: 'bold'}}
                      position='top'/>
                    </Block>
    );
  }
}

在此处输入图像描述

我的 PHP 文件[放置在实时服务器上]

<?php

// Importing DBConfig.php file.
include 'DBConfig.php';

// Creating connection.
 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 // Getting the received JSON into $json variable.
 $json = file_get_contents('php://input');

 // decoding the received JSON and store into $obj variable.
 $obj = json_decode($json,true);

// Populate column from JSON $obj array and store into $coulmn.
$mobileno = $obj['mobileno'];
//Applying User Login query with mobile number match.
$Sql_Query = "select firstname,lastname,email,profession,mobileno from member where mobileno = '$mobileno' ";

// Executing SQL Query.
$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));
$VMNO = $mobileno;
echo $VMNO;

if(isset($check)){


 // $SuccessLoginMsg = 'Data Matched';


 // Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);


$check = json_encode($check);
// Echo the message.
 echo $check ; 
 }

 else{

 // If the record inserted successfully then show the message.
$InvalidMSG = 'Enter valid phone number' ;

// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);

// Echo the message.
 echo $InvalidMSGJSon ;

 }

 mysqli_close($con);
?>

错误是==>

JSON 解析错误:无法解析 JSON 字符串

注意 ==>当我在 Web 浏览器上测试 PHP 文件时,PHP 文件中没有错误,但是当我获取此文件以做出本机反应时,它会导致错误!

在此处输入图像描述

标签: phpjsonreact-nativefetch-api

解决方案


我认为问题在于您通过了在完成您的 JSON 对象时,请删除以下代码的检查。

 navigation.navigate("Profile",{
  mobileno : abc, 
  myJSON: responseJson[0]+ " " +responseJson[1],
  myJSON2: responseJson[2],
  myJSON3: responseJson[3], 
});

它将把你的第三个参数作为你的导航谢谢


推荐阅读