微信小程序篇_01 微信小程序与Java后端接口交互
本文主要介绍小程序前后端数据的交互,实践演示。
准备
创建后端项目
我这里就创建一个SpringBoot项目作为演示。
在创建项目中选择Spring Initializr 要勾选SpringWeb框架,当然你也可以后面导入,确认好设置后,创建项目。
然后在Maven依赖中调整SpringBoot的版本
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <!-- <scope>test</scope>--> </dependency> </dependencies>
目录结构如下,缺少的自行创建: 配置文件application.yml配置如下(仅供参考),
server: port: 80 servlet: context-path: / tomcat: uri-encoding: utf-8
代码HelloWeiXin类(后端接口,在controller层):
测试,然后我们就可以在浏览器访问测试接口 这样我们的后端接口就创建完成了。
创建小程序项目
<!--pages/hello/helloworld.wxml--> <text>后端返回的数据:{ {message}}</text>
js代码如下
// pages/hello/helloworld.js Page({ /** * 页面的初始数据 */ data: { message: "请求中。。。", }, getData() { const that = this wx.request({ url: http://localhost/getMessage, data: { userId: 666 }, method: GET, success(res) { console.log("请求状态:" + res.statusCode) console.log(res.data) that.setData({ message: res.data }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getData() }, })
我对这几行代码有如下解释: wx.request(Object)是请求的方法,具体用法请参考文档中API的网络, 其中url,data,method都是该Object的属性,显而易见,url就是请求的接口地址,data中存放的是请求的参数,method是请求方式,默认是get。 success(response)是一个函数,或者说对象中的方法,它是将请求成功返回来的结果拿回来,也就是回调,回来的就是一个响应对象,数据在响应对象的data属性中,我们操作它。
代码中有几个细节要注意: 我把回调过程都封装在getData方法中,在onLoad方法中调用,onLoad你可以理解为内置方法,它是在页面加载是自动调用的。 其次,在getData方法中使用了另一个对象,这个对象若向访问页面对象,要提前声明个that = this,否则作用域不用,在success方法中this用的就是wx对象了。 如果你遇到如下问题,提示域名不安全,注意这不是跨域问题,只是由于访问的地址没有正规的检查。 你需要手动设置一下开发工具 在右上角的详情,勾选这个 就ok了。 页面和控制台都是正常的了。 这就实现了前后端的交互。