
React NativeでフォームからPHPでPOST送信して入力フォームの値を取得
React Native
import React, { Component } from 'react'; import { AppRegistry, Text, Image, View, Button, StyleSheet, TextInput, Linking, Alert, Navigator } from 'react-native'; import t from 'tcomb-form-native'; const Form = t.form.Form; const Email = t.subtype(t.Str, (email) => { const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return reg.test(email); }); const LoginFields = t.struct({ username: Email, password: t.String, }); const options = { fields: { password: { type: 'password', placeholder: 'Password', }, username: { placeholder: 'e.g: abc@gmail.com', error: 'Insert a valid email' } } }; export default class Login extends Component { _onSubmit() { const value = this.refs.form.getValue(); if (value) { console.log(value.password); console.log(value.username); fetch('https://あなたのサーバー/react_test.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ password: value.password, username: value.username }) }).then((response) => response.json()) .then( (responseJson) => { Alert.alert( responseJson.password.toString() ); Alert.alert( responseJson.username.toString() ); }).catch((error) => { //console.error(error); }); } } render() { return ( <View style={styles.containerView}> <Form ref="form" type={LoginFields} options={options} /> <Text style={{color: 'blue', marginBottom: 10}} onPress={() => Linking.openURL('https://www.google.co.in')}> Forgot Password? </Text> <Button onPress={this._onSubmit.bind(this)} title="sign up" style={styles.loginButton} accessibilityLabel="Ok, Great!" /> </View> ); } }; const styles= StyleSheet.create({ containerView: { flex: 1, justifyContent: 'center', backgroundColor: '#ffebcd', borderStyle: 'solid', borderColor: '#000000' }, loginText: { fontSize: 20, marginBottom: 10 }, inputFields: { fontSize: 20, borderStyle: 'solid', borderColor: '#000000', borderRadius: 30, marginBottom: 10 }, loginButton: { backgroundColor: '#34A853' } });
PHP
<?php $json_string = file_get_contents('php://input'); echo $json_string; $obj = json_decode($json_string); $myObj->password = $obj['password']; $myObj->username = $obj['username']; $myJSON = json_encode($myObj); echo $myJSON;
Xcode
httpを許可
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
参考
Transport security has blocked a cleartext HTTP