微信小程序获取数据库数据并展示在页面上,简单应用
微信小程序获取数据库数据并展示在页面上,简单应用
现在很多小程序后端使用php+mysql数据库,前端使用框架搭建,最近初学微信小程序搭建,急于想了解一下前端如何获取mysql数据并展示在小程序上。
三个文件:
test.js
test.wxml
api.php
前两个文件是小程序端使用的文件,后一个文件是小程序端与后台数据库连接交互接口文件
首先说api.php文件
此文件是连接数据库,获取数据库相关数据,然后把数据转码放出
代码如下:
$link=new mysqli('127.0.0.1','root','root','test');
$link->set_charset("utf8");
if($link->connect_error){
die("连接失败:");
}
$sql="select * from test";
$res=$link->query($sql);
$data=$res->fetch_all();
echo json_encode($data);
数据以数组形式存放,如果要js获取使用需要转码处理json_encode函数
test.js 为获取$data数据并传递给前端页面
代码如下:
Page({
data:{
},
onLoad:function (options){
var that =this;
wx.request({
url:'http://127.0.0.1/api.php',
date:{},
method:'GET',
header:{
'content-Type':'application/json'
},
success: function (res){
that.setData({
data:res.data,
});
}
})
}
})
使用wx.request获取接口传递过来的数据
test.wxml 数据展示
<view wx:for="{{data}}" wx:key="id">
数据字段:{{item}}
</view>
wx:for 获取js传递过来的数据展示到页面上
感谢