微信小程序前后端数据交互

先简单说一下我写的这个危险小程序前后端交互的业务,主要是两个数据:supplyCount和wantBuyCount,分别代表我的车源和我的求购。目前的需求就是小程序向后端发送请求,然后后端从数据库获取车源和求购的数量反馈给小程序,最后将这两个数据显示出来。

因为就两个数据所以处理起来是比较简单的,可以把这个当做小程序前后端交互最基础CRUD方法,属于是打基础的技能。

一 微信小程序发送请求

  1. 根据这个方法,我们可以写出通过用户id查询用户车源和求购数量的请求。首先在data中定义两个变量存储车源和求购数量,如图所示。
  2. 在小程序的js页面中写发送请求的方法,因为请求的数据 需要在页面加载的时候就显示,所以将次方法写在了onLoad页面初始化函数里。并且我们需要从storage缓存中获取用户的id来查询数量,所以先从storage获取user数据,然后通过util.request方法发送请求,最后将请求获得的数据res赋值给data中定义好的两个变量。代码如下。 var user = wx.getStorageSync(user) //从storage缓存中获取用户数据 util.request(api.supplyCount,//url为api中定义好的 {shopId: user.shopId}//返回的数据为用户的shopId ,GET).then(res => {//请求的方法为get,res为获取的数据 this.setData({//将res赋值为data中的supplyCount supplyCount: res }) }) util.request(api.wantBuyCount, {shopId: user.shopId} ,GET).then(res => { this.setData({ wantBuyCount: res }) })
  3. 在xml文件中加入这两个组件,将数据显示出来 <view class=top_nav> <view class=top_column> <view class=top_column_item bindtap=goMySupply data-index=1 data-route=/pages/purchase/purchase> <text class="top_column_item_count">{ {supplyCount}}</text> <view class=user_column_item_text>我的车源</view> </view> <view class="divLine"></view> <view class=top_column_item bindtap=goMyQuote data-index=2 data-route=/pages/purchase/purchase> <text class="top_column_item_count">{ {wantBuyCount}}</text> <view class=user_column_item_text>我的求购</view> </view> </view> </view> 二 后端接口接受小程序请求并返回数据

后端来说比较简单,先在controller层写好和前端请求地址对应的方法,然后再service层写好对应的逻辑方法,即根据shopId查询车源和求购数量,因为我的springboot项目使用了mybatis和mybatis-generator插件,所以实体类domain层和mapper接口层都自动生成了,并且也生成了常用的CRUD方法,可以直接调用,在这里将我的代码附上。

controller层

@RequestMapping("/wx/supply")
public class WxSupplyController {

	@Autowired
	private SupplyService supplyService;

	@GetMapping("count")
	public int count(Integer shopId){
		int number = supplyService.countByshopId(shopId);
		return number;
	}
}

service层

@Service
public class SupplyService {
        @Resource
        private LitemallFormSupplyMapper formSupplyMapper;


        public int countByshopId(Integer shopId){
            LitemallFormSupplyExample example = new LitemallFormSupplyExample();
            LitemallFormSupplyExample.Criteria criteria = example.createCriteria();
            example.or().andShopIdEqualTo(shopId);
            return (int)formSupplyMapper.countByExample(example);
        }
}

 三 最后的效果图

经验分享 程序员 微信小程序 职场和发展