Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php JSON解析错误:尝试返回错误消息时无法解析JSON字符串_Php_Json - Fatal编程技术网

Php JSON解析错误:尝试返回错误消息时无法解析JSON字符串

Php JSON解析错误:尝试返回错误消息时无法解析JSON字符串,php,json,Php,Json,我试图为我的react native register屏幕返回一条错误消息。名为的.php脚本是: <?php include 'DBConfig.php'; // Creating connection. $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); if ($con == false) { $ShitMSG = "Can't connect to database" ; $ShitJs

我试图为我的react native register屏幕返回一条错误消息。名为的.php脚本是:

<?php

include 'DBConfig.php';

// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($con == false) {
  $ShitMSG = "Can't connect to database" ;
  $ShitJson = json_encode($ShitMSG);
  echo $ShitJson ;
}

// 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 User name from JSON $obj array and store into $name.
$name = $obj['name'];
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];

//Checking Email is already exist or not using SQL query.
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)) {
  $EmailExistMSG = "L'E-mail est déja utilisé !";
  $EmailExistJson = json_encode($EmailExistMSG);
  echo $EmailExistJson ;
}
else {
  // Creating SQL query and insert the record into MySQL database table.
  $Sql_Query = "insert into UserRegistrationTable (name,email) values ('$name','$email')";
  if(mysqli_query($con,$Sql_Query)) {
    $MSG = 'Utilisateur enregistré !' ;
    $json = json_encode($MSG);
    echo $json ;
  }
  else {
    echo 'Réessayez';
  }
}
mysqli_close($con);

?>
包括输入我的用户名和电子邮件。php是另一个连接数据库ID的php文件

我的脚本由我的react本机应用程序启动,通过以下功能:

class LoginScreen extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      UserName: '',
      UserEmail: ''
    }
  }

  UserRegistrationFunction () {
    const { UserName } = this.state
    const { UserEmail } = this.state

    fetch('http://c2isante.fr/appsante/login.php', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: UserName,
        email: UserEmail
      })

    }).then((response) => response.json())
      .then((responseJson) => {
        Alert.alert(responseJson)
      }).catch((error) => {
        console.error(error)
      })
  }

  render () {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 20, color: '#000', textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text>
        <TextInput
          placeholder='Entrez votre nom'
          onChangeText={UserName => this.setState({...this.state, UserName})}
          underlineColorAndroid='transparent'
        />
        <TextInput
          placeholder='Entrez votre E-mail'
          onChangeText={UserEmail => this.setState({...this.state, UserEmail})}
          underlineColorAndroid='transparent'
        />
        <Button title="M'enregistrer" onPress={this.UserRegistrationFunction.bind(this)} color='#2196F3' />
      </View>
    )
  }
}
classloginscreen扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
用户名:“”,
用户电子邮件:“”
}
}
UserRegistrationFunction(){
const{UserName}=this.state
const{UserEmail}=this.state
取('http://c2isante.fr/appsante/login.php', {
方法:“POST”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
名称:用户名,
电子邮件:UserEmail
})
}).then((response)=>response.json())
.然后((responseJson)=>{
警报。警报(响应JSON)
}).catch((错误)=>{
控制台错误(错误)
})
}
渲染(){
返回(
用户登记表
this.setState({…this.state,UserName})}
“透明的”
/>
this.setState({…this.state,UserEmail})
“透明的”
/>
)
}
}

在php脚本中,您可以直接对只返回字符串的字符串进行
json\u编码


因此,在javascript中,代码从php文件接收字符串,不能对字符串进行
JSON.parse
。因此,它会给您带来错误。

将字符串编码为json字符串有什么意义。直接回显字符串或创建响应数组并对其进行编码

$x= array(
  "error_code": "404",
  "message": "not found"
);
echo json_encode($x);

PHP有三种可能的结果:

JSON编码的字符串:

$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;
$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;
JSON编码的字符串:

$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;
$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;
纯文本字符串:

echo 'Réessayez';

您应该保持一致:始终将输出编码为JSON或从不将输出编码为JSON

要么:

  • 将第三种情况更改为将结果编码为JSON,就像其他情况一样
  • 将前两个更改为输出纯文本更改JavaScript,使其不会尝试将其解析为JSON


  • 旁白:您没有指定
    标题(“Content-Type:something”)
    ,所以无论您输出的是纯文本还是JSON,您都声称要输出HTML(PHP的默认设置)。您应该解决这个问题。

    您可以在实际检查php脚本输出的地方显示您的react代码吗。立即添加它!:)危险:您很容易受到您需要的源代码的攻击。我知道这一点,但作为php的初学者,我想让原始代码首先工作^^^。我现在只返回JSON语句,正如我的应用程序代码所期望的那样