我的主要任务是创建联系人列表。因此,用户按下按钮,然后用户在屏幕上看到,输入联系人用户的电子邮件,然后如果服务器的响应为“结果=== 0”,则该联系人用户将被成功添加到联系人列表中。如果来自服务器的响应是“结果=== -1”,则由于不存在电子邮件而找不到用户。
一切正常,只有一件事:即使电子邮件错误,也表明用户的响应是成功的。
我找不到我做错了什么。有人可以帮我吗?
这是我的代码:
联系人列表(React Native):
addNewContact = (email) => {
this.setState({
promptVisible: false,
});
if (email === this.props.email) {
Alert.alert('This is your username', 'You cannot add yourself to contacts!');
return;
}
for (var i = 0; i < this.state.contacts.length; i++) {
if (email === this.state.contacts[i].email) {
Alert.alert('Existing Contact', 'Contact ' + email + ' already exists');
return;
}
}
this.showLoading();
fetch('LINK')
.then((response) => response.json())
.then((responseData) => {
this.hideLoading();
var result = responseData.result;
var contactId = responseData.id;
var name = responseData.name;
if (result === 0) {
console.log("Success");
var newContacts = this.state.contacts.slice();
newContacts[newContacts.length] = {
contact_id: contactId,
name: name,
email: email
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newContacts),
contacts: newContacts
});
Alert.alert('Contact added', 'User ' + email + ' was added to your contacts')
console.log(newContacts);
} else {
if (result === -1) {
Alert.alert('Not Found', 'User ' + email + ' not found');
console.log("Bad");
console.log(responseData);
}
}
})
.done;
}
服务器(PHP):
<?php
include 'DBConfig.php';
$conn = new mysqli($Name, $User, $Pass, $Database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$email = $obj['email'];
$sql = "SELECT id, name, email FROM Registration WHERE email='$email'";
$result = mysqli_fetch_array(mysqli_query($conn,$sql));
if (isset($result)) {
$result = array('result' => 0);
echo json_encode($result);
} else {
$result = array('result' => -1);
echo json_encode($result);
}
echo $json;
$conn->close();
?>
upd:我发现控制台中显示:
Success
Array [
Object {
"contact_id": undefined,
"email": "Djdf",
"name": undefined,
},
]