react native 端参考代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
Alert,
TouchableOpacity,
View
} from 'react-native';
//Post方法, 需要请求体body
/*
* FromData
* 主要用于序列化表单以及创建与表单格式相同的数据
*
* var data = new FormData();
* data.append("name","hello");
* append方法接收两个参数,键和值(key,value),分别表示表单字段的名字 和 字段的值,可添加多个
*
* 在jQuery中,"key1=value1&key2=valu2" 作为参数传入对象框架,会自动分装成FormData形式
* 在Fetch 中,进行post进行post请求,需要自动创建FormData对象传给body
*
* */
function postRequest(url) {
//将"key1=value1&key2=valu2" 形式封装整FromData形式
let formData = new FormData();
formData.append("id","15");
formData.append("verName","1111aaaa");
var opts = {
method:"POST", //请求方法
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:formData, //请求体
};
fetch(url , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: formData,
}).then((response) => {
if (response.ok) {
return response.json();
}
}).then((json) => {
console.log(json);
console.log(json.id);
console.log(json.verName);
alert(JSON.stringify(json));
}).catch((error) => {
console.error(error);
})
}
export default class HomeScreen extends Component {
render() {
return(
<View style={styles.container}>
{/*注意: 方法调用方式,绑定了this */}
<TouchableOpacity onPress={postRequest.bind(this,"http://jmbsjk.com/test/test2.php")}>
<View style={styles.btn}>
<Text>Post</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
var styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:'cyan',
marginTop:30,
flexDirection:'row',
justifyContent:'center',
alignItems:'center'
},
btn:{
width:60,
height:30,
borderWidth:1,
borderColor:"yellow",
justifyContent:'center',
alignItems:'center'
}
});
PHP服务器端代码:
<?php
// $json = file_get_contents("php://input");
// $data = json_decode($json, true);
//$id=$data['id'];
$id=$_POST['id'];
$verName=$_POST['verName'];
//链接数据库
$con = mysqli_connect("localhost","my_db","123456",'my_db',3306);
$result = mysqli_query($con,"select * from recordClear where recordId=".$id."");
$num = mysqli_num_rows($result);
//printf("总共返回 %d 行数据。",$num);
// 释放结果集
//mysqli_free_result($result);
//获取星期
$time2 = date("N",time());
//printf("今天:%s",$time2);
$sql = "INSERT INTO recordClear(recordId,recordCount,cleardate) VALUES(".$id.",'1',".$time2.")";
$query = mysqli_query($con,$sql);
mysqli_close($con);
$resulttt = array(
'id'=>$id,
'verName'=>$verName,
);
echo json_encode($resulttt,128);
?>