微信小程序连接数据库
1、登录小程序后台 -> 开发 -> 开发设置 -> 服务器域名设置(协议必须是https或wss,https协议需要开启SSL证书),如图:
若是在本地进行调试,可进行如下设置:
2、.wxml文件中:
<view wx:for="{ {info}}" wx:key="key"> <text>{ {item.id}} { {item.nicheng}} { {item.content}} { {item.time}}</text> </view>
3、.js文件Page中:
/** * 页面的初始数据 */ data: { info: [] //将info的数据传到前台wxml页面中 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this wx.request({ url: http://localhost:88/chat/test.php, //此处不能用https,需勾选不校验合法域名,上线需使用https协议 data: {}, //传参 header: { content-type: application/json }, success: function(res) { console.log(res.data) that.setData({ info: res.data //设置数据,将表中查询出来的信息传给info }) }, fail: function(err) { console.log(err) } }) },
4、后台php页面中:
注意:以下代码php5.4以上才支持。
JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT
结果如下: