发环境 Atom、phpStudy2018、Genymotion (Window10)
一、环境配置
1.1安装Reactnative.
https://reactnative.cn/docs/0.51/getting-started.html#content
1.2Android模拟器Genymotion安装
https://www.cnblogs.com/whycxb/p/6850454.html
二、代码
2.1客户端
2.11App.js
import React, { Component } from ‘react‘; import { AppRegistry, StyleSheet, Text, View } from ‘react-native‘; var GetData = require("./getData"); export default class AwesomeProject extends Component { render() { return ( <GetData></GetData> ); } }
2.12getData.js
import React, { Component } from ‘react‘; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity } from ‘react-native‘; var getUrl = "http://47.104.102.226/public/ajax/admin.php"; var postUrl = "http://192.168.1.177/react/demo.php/"; class getData extends Component{ getRequest(url){ var opts = { method:"GET" } fetch(url,opts) .then((response) => { return response.text(); }) .then((responseText) => { alert(responseText); }) .catch((error) =>{ alert(error); }) } postRequest(url){ var opts = { method: ‘POST‘, headers: { ‘Accept‘: ‘application/json‘, ‘Content-Type‘: ‘application/json‘, }, body: JSON.stringify({ username: ‘userValue‘, password: ‘passValue‘, }) } fetch(url,opts) .then((response) => { return response.text(); }) .then((responseText) => { alert(responseText); }) .catch((error) => { alert(error) }) } render(){ return( <View style={styles.container}> <TouchableOpacity onPress={this.getRequest.bind(this,getUrl)}> <View style={styles.btn}> <Text>GET</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.postRequest.bind(this,postUrl)}> <View style={styles.btn}> <Text>POST</Text> </View> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container:{ backgroundColor:"cyan", flexDirection:"row", justifyContent:"space-around", alignItems:"center", flex:1 }, btn:{ width:60, height:30, borderWidth:1, borderRadius:3, borderColor:"black", backgroundColor:"yellow", justifyContent:"center", alignItems:"center" } }); module.exports = getData;
2.2服务器端
C:\phpStudy\PHPTutorial\WWW\react\demo.php
<?php $json = json_decode(file_get_contents(‘php://input‘), true); $username = $json[‘username‘]; $password = $json[‘password‘]; $response = array("success" => true, "username" => $username, "password" => $password); echo json_encode($response); ?>
三、运行
3.1运行结果
3.2Atom工程结构