以下是【zqyyll】分享的內(nèi)容全文:
微信小程序獲取數(shù)據(jù)庫數(shù)據(jù)并展示在頁面上,簡單應用
現(xiàn)在很多小程序后端使用php+mysql數(shù)據(jù)庫,前端使用框架搭建,最近初學微信小程序搭建,急于想了解一下前端如何獲取mysql數(shù)據(jù)并展示在小程序上。
三個文件:
test.js
test.wxml
api.php
前兩個文件是小程序端使用的文件,后一個文件是小程序端與后臺數(shù)據(jù)庫連接交互接口文件
首先說api.php文件
此文件是連接數(shù)據(jù)庫,獲取數(shù)據(jù)庫相關數(shù)據(jù),然后把數(shù)據(jù)轉碼放出
代碼如下:
$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);
數(shù)據(jù)以數(shù)組形式存放,如果要js獲取使用需要轉碼處理json_encode函數(shù)
test.js 為獲取$data數(shù)據(jù)并傳遞給前端頁面
代碼如下:
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獲取接口傳遞過來的數(shù)據(jù)
test.wxml 數(shù)據(jù)展示
<view wx:for="{{data}}" wx:key="id">
數(shù)據(jù)字段:{{item}}
</view>
wx:for 獲取js傳遞過來的數(shù)據(jù)展示到頁面上

本站不存儲任何資源文件,敬請周知!
本網(wǎng)站采用 BY-NC-SA 協(xié)議進行授權 轉載請注明原文鏈接:微信小程序獲取數(shù)據(jù)庫數(shù)據(jù)并展示在頁面上,簡單應用

侵權舉報/版權申訴



