当前位置:   article > 正文

小程序实现后台数据交互及WXS的使用_小程序与后端如何交互

小程序与后端如何交互

一,数据交互准备工作

1.1 后端准备

后端部分代码,可自行创建后端代码

  1. package com.zking.minoa.wxcontroller;
  2. import com.zking.minoa.mapper.InfoMapper;
  3. import com.zking.minoa.model.Info;
  4. import com.zking.minoa.util.ResponseUtil;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * @Autho donkee
  13. * @Since 2022/6/29
  14. */
  15. @RestController
  16. @RequestMapping("/wx/home")
  17. public class WxHomeController {
  18. @Autowired
  19. private InfoMapper infoMapper;
  20. @RequestMapping("/index")
  21. public Object index(Info info) {
  22. List<Info> infoList = infoMapper.list(info);
  23. Map<Object, Object> data = new HashMap<Object, Object>();
  24. data.put("infoList",infoList);
  25. return ResponseUtil.ok(data);
  26. }
  27. }

pom.xml的配置:

根据自己有更多需求进行应用配置的增加

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.6.2</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.zking</groupId>
  12. <artifactId>minoa</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>minoa</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <fastjson.version>1.2.70</fastjson.version>
  19. <jackson.version>2.9.8</jackson.version>
  20. </properties>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-jdbc</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.mybatis.spring.boot</groupId>
  32. <artifactId>mybatis-spring-boot-starter</artifactId>
  33. <version>2.2.1</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>mysql</groupId>
  37. <artifactId>mysql-connector-java</artifactId>
  38. <version>5.1.44</version>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <optional>true</optional>
  45. </dependency>
  46. <dependency>
  47. <groupId>com.alibaba</groupId>
  48. <artifactId>fastjson</artifactId>
  49. <version>${fastjson.version}</version>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <plugins>
  54. <plugin>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-maven-plugin</artifactId>
  57. <configuration>
  58. <excludes>
  59. <exclude>
  60. <groupId>org.projectlombok</groupId>
  61. <artifactId>lombok</artifactId>
  62. </exclude>
  63. </excludes>
  64. </configuration>
  65. </plugin>
  66. <plugin>
  67. <groupId>org.mybatis.generator</groupId>
  68. <artifactId>mybatis-generator-maven-plugin</artifactId>
  69. <version>1.3.2</version>
  70. <dependencies>
  71. <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
  72. <dependency>
  73. <groupId>mysql</groupId>
  74. <artifactId>mysql-connector-java</artifactId>
  75. <version>${mysql.version}</version>
  76. </dependency>
  77. </dependencies>
  78. <configuration>
  79. <overwrite>true</overwrite>
  80. </configuration>
  81. </plugin>
  82. </plugins>
  83. </build>
  84. </project>

访问所有数据 

1.2 前端工作

 为了后期方便维护,我们先将所有的后端接口通过一个文件来保存,在根目录下新建config文件夹随后建立api.js文件

  1. // 以下是业务服务器API地址
  2. // 本机开发API地址
  3. var WxApiRoot = 'http://localhost:8080/wx/';
  4. // 测试环境部署api地址
  5. // var WxApiRoot = 'http://192.168.0.101:8070/demo/wx/';
  6. // 线上平台api地址
  7. //var WxApiRoot = 'https://www.oa-mini.com/demo/wx/';
  8. module.exports = {
  9. IndexUrl: WxApiRoot + 'home/index', //首页数据接口
  10. SwiperImgs: WxApiRoot+'swiperImgs', //轮播图
  11. MettingInfos: WxApiRoot+'meeting/list', //会议信息
  12. };

1.2.1请求方式的封装

  1. loadMeetingInfos(){
  2. let that=this;
  3. wx.request({
  4. url: api.IndexUrl,
  5. dataType: 'json',
  6. success(res) {
  7. console.log(res)
  8. that.setData({
  9. lists:res.data.data.infoList
  10. })
  11. }
  12. })
  13. }

在/utils/util.js中添加下列代码:

  1. /**
  2. * 封装微信的request请求
  3. */
  4. function request(url, data = {}, method = "GET") {
  5. return new Promise(function (resolve, reject) {
  6. wx.request({
  7. url: url,
  8. data: data,
  9. method: method,
  10. header: {
  11. 'Content-Type': 'application/json',
  12. },
  13. success: function (res) {
  14. if (res.statusCode == 200) {
  15. resolve(res.data);//会把进行中改变成已成功
  16. } else {
  17. reject(res.errMsg);//会把进行中改变成已失败
  18. }
  19. },
  20. fail: function (err) {
  21. reject(err)
  22. }
  23. })
  24. });
  25. }

注意在module.exports中导出和需要使用的页面js中使用时定义:const util = require("../../utils/util")

  1. //首页会议信息的ajax
  2. loadMeetingInfos() {
  3. let that = this;
  4. util.request(api.IndexUrl).then(res => {
  5. this.setData({
  6. lists: res.data.infoList
  7. })
  8. })
  9. }

二,实现数据交互

前端wxml:

  1. <!--index.wxml-->
  2. <view>
  3. <swiper autoplay="true" indicator-dots="true">
  4. <block wx:for="{{imgSrcs}}" wx:key="text">
  5. <swiper-item>
  6. <view>
  7. <image src="{{item.img}}" class="swiper-item" />
  8. </view>
  9. </swiper-item>
  10. </block>
  11. </swiper>
  12. </view>
  13. <view class="mobi-title">
  14. <text class="mobi-icon"></text>
  15. <text class="mobi-text">会议信息</text>
  16. </view>
  17. <block wx:for-items="{{lists}}" wx:for-item="item" wx:key="item.id">
  18. <view class="list" data-id="{{item.id}}">
  19. <view class="list-img">
  20. <image class="video-img" mode="scaleToFill" src="{{item.image !=null? item.image : '/static/persons/6.png'}}"></image>
  21. </view>
  22. <view class="list-detail">
  23. <view class="list-title"><text>{{item.title}}</text></view>
  24. <view class="list-tag">
  25. <view class="state">{{item.state}}</view>
  26. <view class="join"><text class="list-num">{{item.num}}</text>人报名</view>
  27. </view>
  28. <view class="list-info"><text>{{item.location}}</text>|<text>{{item.starttime}}</text></view>
  29. </view>
  30. </view>
  31. </block>
  32. <view class="section">
  33. <text>到底啦</text>
  34. </view>

前端wxss:

  1. /**index.wxss**/
  2. .section{
  3. color: #aaa;
  4. display: flex;
  5. justify-content: center;
  6. }
  7. .list-info {
  8. color: #aaa;
  9. }
  10. .list-num {
  11. color: #e40909;
  12. font-weight: 700;
  13. }
  14. .join {
  15. padding: 0px 0px 0px 10px;
  16. color: #aaa;
  17. }
  18. .state {
  19. margin: 0px 6px 0px 6px;
  20. border: 1px solid #93b9ff;
  21. color: #93b9ff;
  22. }
  23. .list-tag {
  24. padding: 3px 0px 10px 0px;
  25. display: flex;
  26. align-items: center;
  27. }
  28. .list-title {
  29. display: flex;
  30. justify-content: space-between;
  31. font-size: 11pt;
  32. color: #333;
  33. font-weight: bold;
  34. }
  35. .list-detail {
  36. display: flex;
  37. flex-direction: column;
  38. margin: 0px 0px 0px 15px;
  39. }
  40. .video-img {
  41. width: 80px;
  42. height: 80px;
  43. }
  44. .list {
  45. display: flex;
  46. flex-direction: row;
  47. border-bottom: 1px solid #6b6e74;
  48. padding: 10px;
  49. }
  50. .mobi-text {
  51. font-weight: 700;
  52. padding: 15px;
  53. }
  54. .mobi-icon {
  55. border-left: 5px solid #e40909;
  56. }
  57. .mobi-title {
  58. background-color: rgba(158, 158, 142, 0.678);
  59. margin: 10px 0px 10px 0px;
  60. }
  61. .swiper-item {
  62. height: 300rpx;
  63. width: 100%;
  64. border-radius: 10rpx;
  65. }
  66. .userinfo {
  67. display: flex;
  68. flex-direction: column;
  69. align-items: center;
  70. color: #aaa;
  71. }
  72. .userinfo-avatar {
  73. overflow: hidden;
  74. width: 128rpx;
  75. height: 128rpx;
  76. margin: 20rpx;
  77. border-radius: 50%;
  78. }
  79. .usermotto {
  80. margin-top: 200px;
  81. }

三,WXS的使用

    WXS 代码可以编写在 wxml 文件中的 <wxs> 标签内,或以 .wxs 为后缀名的文件内

在wxs中,可以使用一些内置的方法和对象来实现数据处理,如Math、Date等。同时,也可以使用一些自定义的函数和变量来实现特定的业务逻辑

通过后台数据交互和wxs应用,可以实现小程序的数据展示、数据操作和业务逻辑的实现。同时,也可以提高小程序的性能和用户体验

3.1 WXS文件

在项目中的utils文件中创建 .wxs 文件,名为: comm.wxs

comm.wxs代码:

  1. function getState(state){
  2. // 状态:0取消会议1待审核2驳回3待开4进行中5开启投票6结束会议,默认值为1
  3. if(state == 0 ){
  4. return '取消会议';
  5. }else if(state == 1 ){
  6. return '待审核';
  7. }else if(state == 2 ){
  8. return '驳回';
  9. }else if(state == 3 ){
  10. return '待开';
  11. }else if(state == 4 ){
  12. return '进行中';
  13. }else if(state == 5 ){
  14. return '开启投票';
  15. }else if(state == 6 ){
  16. return '结束会议';
  17. }
  18. return '其它';
  19. }
  20. var getNumber = function(str) {
  21. var s = str+'';
  22. var array = s.split(',');
  23. var len = array.length;
  24. return len;
  25. }
  26. function formatDate(ts, option) {
  27. var date = getDate(ts)
  28. var year = date.getFullYear()
  29. var month = date.getMonth() + 1
  30. var day = date.getDate()
  31. var week = date.getDay()
  32. var hour = date.getHours()
  33. var minute = date.getMinutes()
  34. var second = date.getSeconds()
  35. //获取 年月日
  36. if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')
  37. //获取 年月
  38. if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')
  39. //获取 年
  40. if (option == 'YY') return [year].map(formatNumber).toString()
  41. //获取 月
  42. if (option == 'MM') return [mont].map(formatNumber).toString()
  43. //获取 日
  44. if (option == 'DD') return [day].map(formatNumber).toString()
  45. //获取 年月日 周一 至 周日
  46. if (option == 'YY-MM-DD Week') return [year, month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
  47. //获取 月日 周一 至 周日
  48. if (option == 'MM-DD Week') return [month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
  49. //获取 周一 至 周日
  50. if (option == 'Week') return getWeek(week)
  51. //获取 时分秒
  52. if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')
  53. //获取 时分
  54. if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')
  55. //获取 分秒
  56. if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')
  57. //获取 时
  58. if (option == 'hh') return [hour].map(formatNumber).toString()
  59. //获取 分
  60. if (option == 'mm') return [minute].map(formatNumber).toString()
  61. //获取 秒
  62. if (option == 'ss') return [second].map(formatNumber).toString()
  63. //默认 时分秒 年月日
  64. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  65. }
  66. function formatNumber(n) {
  67. n = n.toString()
  68. return n[1] ? n : '0' + n
  69. }
  70. function getWeek(n) {
  71. switch(n) {
  72. case 1:
  73. return '星期一'
  74. case 2:
  75. return '星期二'
  76. case 3:
  77. return '星期三'
  78. case 4:
  79. return '星期四'
  80. case 5:
  81. return '星期五'
  82. case 6:
  83. return '星期六'
  84. case 7:
  85. return '星期日'
  86. }
  87. }
  88. function getNum(canyuze,liexize,zhuchiren){
  89. var person= (canyuze +","+liexize+","+zhuchiren);
  90. return person.split(",").length;
  91. };
  92. module.exports = {
  93. getState: getState,
  94. getNumber: getNumber,
  95. formatDate:formatDate
  96. };

util.js:

  1. const formatTime = date => {
  2. const year = date.getFullYear()
  3. const month = date.getMonth() + 1
  4. const day = date.getDate()
  5. const hour = date.getHours()
  6. const minute = date.getMinutes()
  7. const second = date.getSeconds()
  8. return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
  9. }
  10. const formatNumber = n => {
  11. n = n.toString()
  12. return n[1] ? n : `0${n}`
  13. }
  14. /**
  15. * 封装微信的request请求
  16. */
  17. function request(url, data = {}, method = "GET") {
  18. return new Promise(function (resolve, reject) {
  19. wx.request({
  20. url: url,
  21. data: data,
  22. method: method,
  23. header: {
  24. 'Content-Type': 'application/json',
  25. },
  26. success: function (res) {
  27. if (res.statusCode == 200) {
  28. resolve(res.data);//会把进行中改变成已成功
  29. } else {
  30. reject(res.errMsg);//会把进行中改变成已失败
  31. }
  32. },
  33. fail: function (err) {
  34. reject(err)
  35. }
  36. })
  37. });
  38. }
  39. module.exports = {
  40. formatTime,request
  41. }

再修改首页页面中的 index.wxml  文件,在需要使用的页面进行引用即可 

  1. <wxs src="/utils/comm.wxs" module="tools" />
  2. <view> {{tools.msg}} </view>
  3. <view> {{tools.bar(tools.FOO)}} </view>

3.2 页面

前端首页总代码 

  1. <!-- <wxs src="../../utils/util"> </wxs> -->
  2. <view class="indexbg">
  3. <swiper autoplay="true" indicator-dots="true" indicator-color="#fff" indicator-active-color="#00f">
  4. <block wx:for="{{imgSrcs}}" wx:key="text">
  5. <swiper-item>
  6. <view>
  7. <image src="{{item.img}}" class="swiper-item" />
  8. </view>
  9. </swiper-item>
  10. </block>
  11. </swiper>
  12. <wxs src="/utils/comm.wxs" module="tools" />
  13. <view> {{tools.msg}} </view>
  14. <view> {{tools.bar(tools.FOO)}} </view>
  15. <view class="mobi-title">
  16. <text class="mobi-text">会议信息</text>
  17. </view>
  18. <block wx:for-items="{{lists}}" wx:for-item="item" wx:key="item.id" class="bg">
  19. <view class="list" data-id="{{item.id}}">
  20. <view class="list-img">
  21. <image class="video-img" mode="scaleToFill" src="{{item.image!=null?item.image:'/static/persons/2.jpg'}}"></image>
  22. </view>
  23. <view class="list-detail">
  24. <view class="list-title"><text>{{item.title}}</text></view>
  25. <view class="list-tag">
  26. <view class="state">{{tools.getState(item.state)}}</view>
  27. <view class="join"><text class="list-num">{{tools.getNumber(item.canyuze,item.liexize,item.zhuchiren)}}</text>人报名</view>
  28. </view>
  29. <view class="list-info"><text>{{item.location}}</text>|<text>{{tools.formatDate(item.starttime)}}</text></view>
  30. </view>
  31. </view>
  32. </block>
  33. <view class="section">
  34. <text>到底啦</text>
  35. </view>
  36. </view>

效果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/464818
推荐阅读
相关标签
  

闽ICP备14008679号