//index.wxml
<form bindsubmit="formSubmit" bindreset="formReset">
<view class="section">
<view class="section__title">姓名</view>
<input name="xingming" placeholder="请输入姓名" value='{{xingming}}'/>
</view>
<view class="btn-area">
<button formType="submit">提交</button>
<button formType="reset" >重置</button>
</view>
</form>
<view wx:for="{{list}}" wx:key="list">
<view>{{item.xingming}}</view>
</view>
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
//xingming:''
},
onLoad:function(res){
var th=this; //成功后数据改变,复制对象
wx:wx.request({
url: 'http://1.weiming.applinzi.com/wx/wx.php',
header: {
'content-type':'application/json'
},
method: 'GET',
success: function(res) {
console.log(res);
th.setData({
list:res.data
})
},
fail: function(res) {
console.log("-----fail-----");
},
complete: function(res) {},
})
},
formSubmit: function (e) {
//console.log(e.detail.value);
var that = this;
var formData = e.detail.value;
if (e.detail.value.xingming.length == 0 || e.detail.value.xingming.length >= 8) {
wx.showToast({
title: '姓名不能为空或过长!',
icon: 'loading',
duration: 1500
})
setTimeout(function () {
wx.hideToast()
}, 2000)
}
else{
wx.request({
url: 'http://1.weiming.applinzi.com/wx/wx.php',
data:formData,
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: {
xingming: e.detail.value.xingming
},
success: function (res) {
console.log(res.data);
if (res.data.status == 0) {
wx.showToast({
title: '提交失败!!!',
icon: 'loading',
duration: 1000
})
} else {
wx.showToast({
title: '提交成功!!!',//这里打印出登录成功
icon: 'success',
duration: 1000
})
that.setData({
xingming:'' //input框清空
}
)
}
}
})
}
}
})
后台php:
<?php
$host=SAE_MYSQL_HOST_M;
$port=SAE_MYSQL_PORT;
$user =SAE_MYSQL_USER;
$pass =SAE_MYSQL_PASS;
$bdname =SAE_MYSQL_DB;
$con = mysqli_connect($host, $user, $pass, $bdname , $port); //建立连接
if(!$con)
{
die('建立连接失败:' . mysqli_connect_error());
}
else
{
mysqli_query($con,'set names "utf8"');
mysqli_select_db($con,$bdname); //选择需使用的数据库
if (!empty($_POST['xingming']))
{
$sql="INSERT INTO person (xingming) VALUES ('$_POST[xingming]')";
$result = mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_connect_error());
}
}
$sql1 = "SELECT * FROM person";
$result1 = mysqli_query($con,$sql1);
$data= $result1->fetch_all(PDO::FETCH_LAZY);
echo json_encode($data);//以json形式返回
}
?>