PHP实现小程序跳转传值–回调success的值
在success回调函数里使用this.setData()更新数据时报错,源码及报错位置如下图所示
解决方案
接下来就是跳转传值,传的值较少可以直接通过url实现,较多的话就要利用到后台查询了,我用的页面是原先写的登陆页面再上两篇文章里面有,通过登陆成功进行跳转传值。
index.js
Page({
data: {
},
login: function (e) {
wx.request({
url: 'http://127.0.0.1/login.php',//不要用localhost必须用127.0.0.1来访问--本地不支持HTTPS
method: "get",
header: {
'content-type': 'application/json'
},
data: {
"username": e.detail.value.username,
"password": e.detail.value.password
},
success(res) {
if (res.data['0'].uid != undefined && res.data['0'].uname == e.detail.value.username) {
wx.redirectTo({
// url: '/pages/logs/logs?uid=' + res.data["0"].uid +'&uname='+res.data['0'].uname,//传的值较少可以使用url
url: '/pages/logs/logs?uid=' + res.data["0"].uid //传的值较多可以使用后台查询
})
} else {
wx.showToast({
title: '登陆失败',
icon: 'none'
})
}
}
})
}
})
.wxml和PHP代码我就不放上去了上两篇文章的登陆页面有的,接下来就是登陆成功跳转传值的页面需要传很多值就要运用后台的 废话不多说了 直接上代码
logs.wxml
<form bindsubmit="liuyanban">
<button form-type="submit">提交留言</button>
</form>
logs.js
Page({
data: {
},
/**
* 生命周期函数--监听页面加载---获取从其他页面传来的值经行接收
*/
onLoad: function(options) {
// this.setData({
// uid: options.uid,
// uname: options.uname,//传过来的值较少可以使用url
// })
var that = this//想用setData调用success的值必须要把this给另外一个赋值
this.setData({
uid: options.uid
})
wx.request({
url: 'http://127.0.0.1/liuyanban.php',
method: "get",
data: {
"uid": that.data.uid,
},
success(res) {
console.log('查询数据:', res.data['0'])
that.setData({
uname: res.data['0'].uname//因为uid已经从其他页面传过来了就不用再传uid了
})
}
})
},
liuyanban: function(e) {
console.log('uid:', this.data.uid)
console.log('uname:', this.data.uname)
}
})
.php
<?php
header('content-type:text/html;charset=utf-8');
session_start();
try {
$link = new PDO('mysql:host=localhost;port=3306;dbname=wt_kp5b', 'root', 'root');
//数据库名什么的记得改成你自己的
$link -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('数据库连接出错:' . $e -> getMessage());
}
$sql = 'select * from wt_user where uid=?';
try{
$stmt = $link->prepare($sql);
$stmt->execute([$_GET['uid']]);
if($stmt->rowCount() > 0){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['uid'] = $row['uid'];
$_SESSION['uname'] = $row['uname'];
echo json_encode([$_SESSION]);//要转成json格式给小程序才可以
}
}catch(PDOException $e){
die('用户登陆查询出错:'.$e->getMessage());
}
?>
需要注意的都注释好的,有什么问题欢迎评论留言,我会及时回复你的。