【微信小程序】6天精准入门(第5天:利用案例与后台的数据交互)附源码

news2024/10/5 15:27:21

一、什么是后台交互?

        在小程序中,与后台交互指的是小程序前端与后台服务器之间的数据通信和请求处理过程。通过与后台交互,小程序能够获取服务器端的数据、上传用户数据、发送请求等。

        小程序与后台交互可以实现数据的传输、用户认证、实时消息推送等功能,为用户提供更丰富的体验和功能。

与后台交互可以通过以下方式实现:

  1. 发起网络请求:小程序可以使用网络请求 API(如wx.request)向后台发送 HTTP 请求,来获取后台服务器返回的数据。可以使用 GET、POST、PUT、DELETE 等不同的请求类型来实现不同的操作。
  2. WebSocket:小程序可以使用 WebSocket 技术与服务器建立长连接,实现实时的双向通信。通过 WebSocket,小程序能够及时接收服务器端推送的消息,实现实时更新和交互。
  3. 云函数:小程序提供了云开发平台,其中的云函数可以在后台服务器上执行,用于处理复杂的业务逻辑和数据处理。小程序可以通过调用云函数来与后台进行交互,并获取处理结果。

二、后台数据交互与request封装

1、准备工作

  • 在使用数据交互的时候我们要事先准备好后台的数据方便我们进行调用。
  • 我在这里就不准备后台的数据在这里了

2、后台数据交互

1、在前面的博客里面编写了一个专门用来调用数据后台的一个api.js文件,我们要确保这些数据可以调用到后台,记得把你的后台启动哦!

// 以下是业务服务器API地址
 // 本机开发API地址
 var WxApiRoot = 'http://localhost:8080/wx/';
 
 module.exports = {
   IndexUrl: WxApiRoot + 'home/index' //首页数据接口
 };

2、在你要调用的页面的js里面编写调用的方法,注意记得打印一下你的数据是在那个属性里面,记得在Page的外面调用实用例

// 获取应用实例
const app = getApp()
const api = require("../../config/api")
 //首页会议信息的ajax
    loadMeetingInfos() {
        let that = this;
         wx.request({
             url: api.IndexUrl,
             dataType: 'json',
             success(res) {
                 console.log(res)
                 that.setData({
                     lists: res.data.data.infoList
                 })
             }
         })

    }

然后再定义好的onLoad方法里面调用

    onLoad() {
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
        this.loadMeetingInfos();
    }

3、request封装

  1. 在我们项目的里面有个utils/util,js文件,在里面进行一个方法编写。
    
    /**
     * 封装微信的request请求
     */
    function request(url, data = {}, method = "GET") {
        return new Promise(function (resolve, reject) {
            wx.request({
                url: url,
                data: data,
                method: method,
                header: {
                    'Content-Type': 'application/json',
                },
                success: function (res) {
                    if (res.statusCode == 200) {
                        resolve(res.data);//会把进行中改变成已成功
                    } else {
                        reject(res.errMsg);//会把进行中改变成已失败
                    }
                },
                fail: function (err) {
                    reject(err)
                }
            })
        });
    }
    module.exports = {
        formatTime,request
    }
  2. 在你的需要调用的页面进行一个方法的调用进行代码的优化;就以上为例:

    // 获取应用实例
    const app = getApp()
    const api = require("../../config/api")
    const util = require("../../utils/util.js")
     //首页会议信息的ajax
        loadMeetingInfos() {
            let that = this;
    
            util.request(api.IndexUrl).then(res => {
                console.log(res)
                this.setData({
                    lists: res.data.infoList
                })
            }).catch(res => {
                console.log('服器没有开启,使用模拟数据!')
            })
        }

  3. 效果也是一样的,只是进行了一个代码的优化。

这里提供完整的代码

util.js

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

/**
 * 封装微信的request请求
 */
function request(url, data = {}, method = "GET") {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: url,
            data: data,
            method: method,
            header: {
                'Content-Type': 'application/json',
            },
            success: function (res) {
                if (res.statusCode == 200) {
                    resolve(res.data);//会把进行中改变成已成功
                } else {
                    reject(res.errMsg);//会把进行中改变成已失败
                }
            },
            fail: function (err) {
                reject(err)
            }
        })
    });
}
module.exports = {
    formatTime,request
}

index.js

// index.js
// 获取应用实例
const app = getApp()
const api = require("../../config/api")
const util = require("../../utils/util.js")
Page({
    data: {
        imgSrcs: [{
            "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner1.png",
            "text": "1"
        },
        "lists": []
    },
    //首页会议信息的ajax
    loadMeetingInfos() {
        let that = this;
        util.request(api.IndexUrl).then(res => {
            console.log(res)
            this.setData({
                lists: res.data.infoList
            })
            console.log(res.data.infoList)
        }).catch(res => {
            console.log('服器没有开启,使用模拟数据!')
        })
    },
    onLoad() {
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
        this.loadMeetingInfos();
    }
})

三、wxs的使用

我们可以在微信的开发文档里面可以查看到微信开放文档,wxs的使用。

1、使用wxs步骤

  1. 我们首先新建一个wxs文件在一个位置
  2. 然后在里面定义方法
    function getState(state){}
    module.exports = {
        getState: getState
    };
  3. 在wxml里面调用,src:是你的wxs的路径;module:你后面需要调用的名字,可以随便取。
        <wxs src="/utils/comm.wxs" module="tools" />
  4. 调用

    <text class="list-num">{{tools.getState(item.state)}}</text>

2、完整方法

wxs


function getState(state) {
    // 状态:0取消会议1待审核2驳回3待开4进行中5开启投票6结束会议,默认值为1
    if (state == 0) {
        return '取消会议';
    } else if (state == 1) {
        return '待审核';
    } else if (state == 2) {
        return '驳回';
    } else if (state == 3) {
        return '待开';
    } else if (state == 4) {
        return '进行中';
    } else if (state == 5) {
        return '开启投票';
    } else if (state == 6) {
        return '结束会议';
    }

    return '其它';

}
function getNumber(canyuze, liexize, zhuchiren) {
    var person = canyuze + ',' + liexize + ',' + zhuchiren;
    return person.split(',').length;
}
function formatDate(ts, option) {
    var date = getDate(ts)
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var week = date.getDay()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    //获取 年月日
    if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')

    //获取 年月
    if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')

    //获取 年
    if (option == 'YY') return [year].map(formatNumber).toString()

    //获取 月
    if (option == 'MM') return [mont].map(formatNumber).toString()

    //获取 日
    if (option == 'DD') return [day].map(formatNumber).toString()

    //获取 年月日 周一 至 周日
    if (option == 'YY-MM-DD Week') return [year, month, day].map(formatNumber).join('-') + ' ' + getWeek(week)

    //获取 月日 周一 至 周日
    if (option == 'MM-DD Week') return [month, day].map(formatNumber).join('-') + ' ' + getWeek(week)

    //获取 周一 至 周日
    if (option == 'Week') return getWeek(week)

    //获取 时分秒
    if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')

    //获取 时分
    if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')

    //获取 分秒
    if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')

    //获取 时
    if (option == 'hh') return [hour].map(formatNumber).toString()

    //获取 分
    if (option == 'mm') return [minute].map(formatNumber).toString()

    //获取 秒
    if (option == 'ss') return [second].map(formatNumber).toString()

    //默认 时分秒 年月日
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function getWeek(n) {
    switch (n) {
        case 1:
            return '星期一'
        case 2:
            return '星期二'
        case 3:
            return '星期三'
        case 4:
            return '星期四'
        case 5:
            return '星期五'
        case 6:
            return '星期六'
        case 7:
            return '星期日'
    }
}
module.exports = {
    getState: getState,
    getNumber: getNumber,
    formatDate:formatDate
};

index.wxml

<view class="indexbg">
    <swiper autoplay="true" indicator-dots="true" indicator-color="#fff" indicator-active-color="#00f">
        <block wx:for="{{imgSrcs}}" wx:key="text">
            <swiper-item>
                <view>
                    <image src="{{item.img}}" class="swiper-item" />
                </view>
            </swiper-item>
        </block>
    </swiper>
    <wxs src="/utils/comm.wxs" module="tools" />
    <view class="mobi-title">
        <text class="mobi-icon">❤</text>
        <text class="mobi-text">会议信息</text>
    </view>
    <block wx:for-items="{{lists}}" wx:for-item="item" wx:key="item.id" class="bg">
        <view class="list" data-id="{{item.id}}">
            <view class="list-img">
                <image class="video-img" mode="scaleToFill" src="{{item.image != null ? item.image:'/static/persons/8.jpg'}}"></image>
            </view>
            <view class="list-detail">
                <view class="list-title"><text>{{item.title}}</text></view>
                <view class="list-tag">
                    <view class="state">{{tools.getState(item.state)}}</view>
                    <view class="join"><text class="list-num">{{tools.getNumber(item.canyuze,item.liexize,item.zhuzhiren)}}</text>人报名</view>
                </view>
                <view class="list-info"><text>{{item.location}}</text>|<text>{{tools.formatDate(item.starttime,'YY-MM-DD hh-mm-ss')}}</text></view>
            </view>
        </view>
    </block>
    <view class="section">
        <text>到底啦</text>
    </view>
</view>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1119834.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Babylonjs学习笔记(一)——搭建基础场景

React typescript umi Babylonjs 搭建基础场景 yarn add --save babylonjs babylonjs-loaders 1、封装基础场景 import { Engine, Scene } from "babylonjs"; import { useEffect,useRef,FC } from "react"; import "./index.less"type Prop…

自用bat脚本,命令

redis配置环境变量后 关机脚本 redis-server --service-stop启动脚本 :: 注释 rem echo off cd /d d:\\Redis :: redis-cli :: shutdown :: exit :: netstat -ano |findstr "6639" :: taskkill /pid {pid} /F redis-server redis.windows.conf pausecmd中替代gr…

BFS专题8 中国象棋-马-无障碍

题目&#xff1a; 样例&#xff1a; 输入 3 3 2 1 输出 3 2 1 0 -1 4 3 2 1 思路&#xff1a; 单纯的BFS走一遍即可&#xff0c;只是方向坐标的移动变化&#xff0c;需要变化一下。 代码详解如下&#xff1a; #include <iostream> #include <vector> #include…

上次的那段代码后续

之前写了一篇文章&#xff0c;说是一个要修改一个代码&#xff0c;很多人评论说代码说得不清不楚&#xff0c;不过在评论说又解释了一波之后&#xff0c;大家至少对这个代码有理解了&#xff0c;至少知道这个代码是做什么事情了。 如果是你&#xff0c;会不会修改这段代码&…

数据结构初阶——时间复杂度

朋友们我们又见面了&#xff0c;今天我们来学习数据结构的时间复杂度&#xff0c;在讲数据结构之前&#xff0c;大家可能只知道我们学习的是数据结构&#xff0c;但是还是不知道数据结构的具体定义&#xff0c;其实就是在内存上的数据。然后我们就像通讯录一样对它进行增删查改…

Qt 目录操作(QDir 类)及展示系统文件实战 QFilelnfo 类介绍和获取文件属性项目实战

一、目录操作(QDir 类) QDir 类提供访问系统目录结构 QDir 类提供对目录结构及其内容的访问。QDir 用于操作路径名、访问有关路径和文件的信息以及操作底层文件系统。它还可以用于访问 Qt 的资源系统 Qt 使用“/”作为通用目录分隔符&#xff0c;与“/”在 URL 中用作路径分…

istio介绍(一)

1. 概念 1.1 虚拟服务 虚拟服务提供流量路由功能&#xff0c;它基于 Istio 和平台提供的基本的连通性和服务发现能力&#xff0c;让您配置如何在服务网格内将请求路由到服务 示例&#xff1a; apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata:nam…

高项.项目管理经验、理念、教训

一、项目管理的一些经验 管项目重在管理&#xff0c;而不是死抠无关紧要的技术细节等等。 真正的团队一定是11>2&#xff0c;要把重心放在凝聚团队协力&#xff0c;共同完成目标上。 项目的推进永远都是不确定性的&#xff0c;真正考验项目经理的是不断出现的需求变更和状…

vue重修之路由【上】

文章目录 单页应用程序: SPA - Single Page Application路由简介Vue Reouter简介VueRouter的使用&#xff08;52&#xff09;组件的存放目录问题组件分类存放目录 路由的封装抽离 单页应用程序: SPA - Single Page Application 单页面应用(SPA): 所有功能在 一个html页面 上 单…

常用的跨域解决方案有哪些?

在 Web 开发中,跨域是指在浏览器环境下,通过 JavaScript 代码从一个域名的网页去访问另一个域名的资源。由于同源策略的限制,跨域请求通常会被浏览器阻止,为了实现跨域访问,HTML5 提供了一些机制来解决这个问题。 以下是一些常用的跨域解决方案: 1:JSONP(JSON with P…

展馆导览系统之AR互动式导航与展品语音讲解应用

一、项目背景 随着科技的进步和人们对于文化、艺术、历史等方面需求的提升&#xff0c;展馆在人们的生活中扮演着越来越重要的角色。然而&#xff0c;传统的展馆导览方式&#xff0c;如纸质导览、人工讲解等&#xff0c;已无法满足参观者的多元化需求。为了提升参观者的体验&a…

​CUDA学习笔记(六)Warp解析

本篇博文转载于https://www.cnblogs.com/1024incn/tag/CUDA/&#xff0c;仅用于学习。 Warp 逻辑上&#xff0c;所有thread是并行的&#xff0c;但是&#xff0c;从硬件的角度来说&#xff0c;实际上并不是所有的thread能够在同一时刻执行&#xff0c;接下来我们将解释有关wa…

​CUDA学习笔记(五)GPU架构

本篇博文转载于https://www.cnblogs.com/1024incn/tag/CUDA/&#xff0c;仅用于学习。 GPU架构 SM&#xff08;Streaming Multiprocessors&#xff09;是GPU架构中非常重要的部分&#xff0c;GPU硬件的并行性就是由SM决定的。 以Fermi架构为例&#xff0c;其包含以下主要组成…

什么是SpringMVC?简单好理解!

1、SpringMVC是什么&#xff1f; SpringMVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级web框架&#xff0c;通过把Model&#xff0c;View&#xff0c;Controller分离&#xff0c;将web层进行职责解耦&#xff0c;把复杂的web应用分成逻辑清晰的几部分。简化开发&…

并发编程-线程池ThreadPoolExecutor底层原理分析(一)

问题&#xff1a; 线程池的核心线程数、最大线程数该如何设置&#xff1f; 线程池执行任务的具体流程是怎样的&#xff1f; 线程池的五种状态是如何流转的&#xff1f; 线程池中的线程是如何关闭的&#xff1f; 线程池为什么一定得是阻塞队列&#xff1f; 线程发生异常&…

蓝桥杯 (饮料换购,C++)

思路&#xff1a; 1、先加上初始的饮料数n。 2、再加上n可以兑换的饮料数n/3&#xff0c;求多余的瓶盖n%3。循环直至瓶盖数无法兑换新的一瓶饮料。 #include<iostream> using namespace std; int main() {int n,a0,sum0;cin >> n;sum n;while (n){n n a;//加上上…

【软考】11.5 测试原则/阶段/测试用例设计/调试

《测试原则和方法》 测试原则 测试&#xff1a;为了发现错误而执行程序的过程成功的测试&#xff1a;发现了至今尚未发现的错误的测试 测试方法 静态测试&#xff08;有效发现30%-70%的错误&#xff09; a. &#xff08;文档&#xff09;检查单 b. &#xff08;代码&#xff…

学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例

要想通过SpringBoot写一个简单的处理请求的服务器&#xff08;方法&#xff09;&#xff0c;需要有以下步骤 建立连接请求响应 来复习的话直接在文章末尾看源码就行 1、创建SpringBoot项目 https://blog.csdn.net/dream_ready/article/details/133948253 2、编写Controller建…

WebSocket的入门秘籍?

一、是什么 WebSocket&#xff0c;是一种网络传输协议&#xff0c;位于OSI模型的应用层。可在单个TCP连接上进行全双工通信&#xff0c;能更好的节省服务器资源和带宽并达到实时通迅 客户端和服务器只需要完成一次握手&#xff0c;两者之间就可以创建持久性的连接&#xff0c…

postman打开后,以前的接口记录不在,问题解决

要不这些文件保存在C:\Users\{用户名}\AppData\Roaming\Postman 比如&#xff0c;你目前使用的window登录用户是abc&#xff0c;那么地址便是C:\Users\abc\AppData\Roaming\Postman 打开后&#xff0c;这个目录下会有一些命名为backup-yyyy-MM-ddThh-mm-ss.SSSZ.json类似的文…