主要内容:实现微信小程序与PHP后台之间的数据传递
本文通过from表单提交到后台存入数据库来展现
需要注意的有:
勾选
代码如下:
demo1.wxml
<!--pages/demo1/demo1.wxml-->
<form bindsubmit='formSubmit' bindreset='formReset'><view class="container"><view class="login-from"><!--姓名--><view class="inputView"><label class="loginLab">姓名</label><input class="inputText" name="name" placeholder="请输入姓名" /></view><view class="line"></view><!--手机号--><view class="inputView"><label class="loginLab">手机号</label><input class="inputText" name="mobile" placeholder="请输入手机号" /></view><!--登录按钮--><view class="loginBtnView"><button class="loginBtn" catchtap="submit" type="primary" form-type='submit'>提交</button><button class="loginBtn" type="primary" form-type='reset'>重置</button></view></view></view>
</form>
demo1.wxss
/* pages/demo1/demo1.wxss */
page{height: 100%;
}.container {height: 70%;display: flex;flex-direction: column;padding: 0;box-sizing: border-box;background-color: #f2f2f2
} /*表单内容*/
.login-from {margin-top: 20px;flex: auto;height:100%;
}.inputView {background-color: #fff;line-height: 44px;
}
/*输入框*/
.nameImage, .keyImage {margin-left: 22px;width: 14px;height: 14px
}.loginLab {margin: 15px 15px 15px 10px;color: #545454;font-size: 14px
}
.inputText {flex: block;float: right;text-align: right;margin-right: 22px;margin-top: 11px;color: #cccccc;font-size: 14px
}/*按钮*/
.loginBtnView {width: 750rpx;height: 750rpx;background-color: #f2f2f2;margin-top: 0px;margin-bottom: 0px;padding-bottom: 0px;
}.loginBtn {width: 350rpx;margin-top: 15rpx;margin-left: 17rpx;float: left;
}
demo1.js
//var url = 'http://wxtest.com/index.php/index'//tp5
var url = 'http://localhost/wxphp/form.php'//源生
Page({data: {},formSubmit: function (e) {var that = thiswx.request({url: url,data: {'name': e.detail.value.name,'mobile': e.detail.value.mobile,},method: 'GET',header: {'content-type': 'application/json'},success: function (res){console.log(1111);console.log(res.data.status);if (res.data.status == 1) {wx.showToast({title: res.data.info,duration: 2000});}else{wx.showToast({title: '提交失败',duration: 2000});}},})}
})
PHP后台代码分两种方式接收:源生和TP5.1框架
源生:
from.php
<?php
//设置编码utf—8
header('Content-type:text/html;charset=utf-8');
//接收数据
$name = $_GET['name'];
$mobile = $_GET['mobile'];
//连接数据库
$con = new mysqli("localhost","root","root","wxphp");
//定义sql语句
$sql = "INSERT INTO user(name,mobile) values('$name','$mobile ');";
//发送sql语句
$res = mysqli_query($con,$sql);
if($res){$arr['status'] = 1;$arr['info'] = '提交成功';
}else{$arr['status'] = 0;$arr['info'] = '提交失败';
}
echo json_encode($arr);
die;
TP5.1:
<?php
namespace app\index\controller;
use think\Db;class Index
{public function index(){//接收数据$data = input('post.');//将数据存入数据库$res = Db::name('user')->insert($data);//将结果反馈给前台if($res){$arr['status'] = 1;$arr['info'] = '提交成功';}else{$arr['status'] = 0;$arr['info'] = '提交失败';}echo json_encode($arr);die;
}
本案例只是简单地将数据从微信小程序前台提交给PHP后台,然后后台将数据存入数据库,没有过多地验证规则
效果图如下: