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);
?>