微信小程序调接口傻瓜式记录(包含onload页面加载发请求渲染页面、发送短信验证码、表单提交、根据id值跳转对应详情页等调接口情况)

最近接触了微信小程序项目,只是写了前端的样式页面,一直不懂接口是怎么调的,这很惭愧,也不应该。所以就研究一下,记录我所理解的过程
给自己做个笔记,也希望能给跟我一样没有和后段对接调接口经验的小白提供一些帮助,当然,如果有理解不对的地方还请见谅,期待指出

一直都不理解接口到底是个什么东西,在我的理解里,暂且是把它看作后端小哥哥写的一些数据和逻辑的地址
此项目中可以把所有用到的接口放在一个文件内,再封装一个ajax请求方法,用微信小程序自带的wx.request肯定也是可以的
在这里插入图片描述

request.js

import api from '../core/api.js'
function ajax(method, url, option) {
  wx.showLoading({
    title: '加载中...'
  });
  return new Promise((resolve, reject) => {
    wx.request({
      url: api[url],
      method: method,
      dataType: 'json',
      data: option,
      header: {
        'content-type': 'application/json', // 默认值
        'Token': wx.getStorageSync('token') || ''
      },
      success: res => {
        wx.hideLoading();
        let statusCode = res.statusCode
        if (statusCode >= 200 && statusCode < 300) {
          resolve(res.data)
        } else if (statusCode == 602 || statusCode == 603) {
          wx.showToast({
            title: res.resultMsg,
            icon: 'none',
            duration: 2000
          })
          wx.redirectTo({
            url: '/pages/authorize/authorize',//授权页面
          })
        } else {
          reject(res.data)
        }
      },
      fail: err => {
        console.log(err)
      }
    });
  })
}
module.exports = {
  ajax: ajax
}

以下列举了几个调接口的情况 具体分析

1.页面加载时就需要调用某接口进行渲染 如下,对picker组件内容进行渲染(同时这里还展示了怎么判断授权登录状态的功能,默认展示首页,判断是否授权 若没有跳转授权页面)

index.wxml

	<view class="section">
         <view class="section__title require">被投诉项目:</view>
           <picker class="section__value" bindchange="bindPickerChange" range-key="{{'proName'}}" value="{{multiArray[idx].id}}" range="{{multiArray}}">
             <view class="picker">
                {{multiArray[idx].proName}}
             </view>
          </picker>
    </view>

index.js

引入模块

import requests from '../../core/request.js'
onLoad: function () {
    var that = this;
    // 判断是否已经授权
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userInfo']) {//未授权,跳到授权页面
          wx.redirectTo({
            url: '../authorize/authorize',//授权页面
          })
        }
      }
    })
    //主要是调接口拿数据 然后存起来 渲染页面
    requests.ajax('GET', 'queryByPro(后端接口名)', { proName :""}).then(res => {
      console.log(res)
      this.setData({
        multiArray: res.data //data中已经的定义一个空数组
      })
    })
  }

2.发送短信验证码 调发验证码接口
index.wxml

<view class="section">
              <view class="section__title require">联系方式:</view>
              <input type="number" name="tel" cursor-spacing="30rpx" data-key="form.tele" bindblur="isPhone"  bindchange="bindChange" />
          </view>
          <view class="section">
              <view class="section__title require">验证码:</view>
              <input type="number" name="uniqueCode" cursor-spacing="30rpx" data-key="form.uniqueCode" bindchange="bindChange" />
              <view bindtap="getCaptcha" class="get-captcha {{wait?'wait':''}}">{{captcha}}</view>
          </view>

index.js

  getCaptcha(){
    if (this.data.form.tele) {
      if (!this.data.isPhoneFlag) { //isPhoneFlag是手机号正则验证函数 这里就不展示了
        wx.showToast({
          title: '联系方式格式有误',
          icon: 'none',
          duration: 2000,
        })
        return 
      }
      if (this.data.wait) {
        return
      }
      let waitSec = 60
      let timeout = 1000
      this.timer = setInterval(() => {
        waitSec--
        this.setData({ wait: true })
        this.setData({ captcha: '重新发送' + waitSec + '秒' })
        if (waitSec <= 0) {
          clearInterval(this.timer)
          this.setData({ wait: false })
          this.setData({ captcha: '获取验证码' })
        }
      }, timeout)
      
      //携带手机号给后端 也是主要是把数据给后端,具体的发送验证码逻辑由后端完成
      requests.ajax('POST', 'sendMessage', {tele: this.data.form.tele }).then(res => {
        wx.showToast({
          title: res.resultMsg,
          icon: 'none',
          duration: 2000,
        })
      })
      
    } else {
      wx.showToast({
        title: '联系方式不可为空',
        icon: 'none',
        duration: 2000
      })
      return ;
    }
   
  }

3.表单提交


//<form bindsubmit="formSubmit" >......</form>
formSubmit: function(e) {
    var valueArray = e.detail.value;//拿到表单信息   
    //下面进行提交表单到后台
    let params = { //这些都是参数 都放在params这个对象里,发ajax掉后台接口时传给后台,给他们处理 储存
      complainMan: valueArray.userName,
      tele: valueArray.tel,
      ids: valueArray.idcard,
      code: valueArray.uniqueCode,
      address: valueArray.address,
      complainCompany: valueArray.company,
      complainPro: this.data.multiArray[this.data.idx].id,
      workType: valueArray.workType,
      proManager: valueArray.manager,
      proManagerTele: valueArray.managerTel,
      approachTime: valueArray.startDate,
      exitTime: valueArray.endDate,
      complainContent: valueArray.report,
      complainFiles: JSON.stringify(arr)
    }
    requests.ajax('POST', 'insert', params).then(res => {
      //console.log(res)
      if (res.resultCode == 200) { //200表示请求成功 下面清空表单 这个接口主要是把我们的表单内容提交到后台,所以没有用到接口里太多的东西,只要判断浒苔传来的resultCode是否为200即可)
        this.setData({
          images: []
        })
        this.setData({
          idx: 0
        })
        console.log(this)
        this.setData({
          'form.userName': ''
        })
        console.log(this)
        this.setData({
          form: {
            userName: '',
            idcard: '',
            tele: '',
            uniqueCode: '',
            address: '',
            company: '',
            item: '',
            workType: '',
            manager: '',
            managerTel: '',
            startDate: '',
            endDate: '',
            report: ''
          }
        })
      }
      wx.showToast({
        title: res.resultMsg, //提示成功消息 也是接口中返回的数据
        icon: 'none',
        duration: 2000
      })
    })
  }

4.根据id值跳转对应详情页

history.wxml

<view class="table" bindtap="toDetail" data-id="{{item.id}}"> 
            <view class="tr">
                <view class="td f_2">姓名</view>
                <view class="td f_4">{{item.complainMan}}</view>
            </view>
 </view>

这里data-id 其实是利用data-* 定义了一个自定义属性id 然后将循环的item的id赋值给自定义属性id
下面js中就可以把这个id当做跳转的唯一标识

history.js

toDetail: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/detail/detail?projecturl=' + e.currentTarget.dataset.id
    })
  }

console.log(e) 打印内容如下:
在这里插入图片描述
detail.js

//页面加载时发送请求 携带唯一id标识信息,接口返回与此id唯一对应的数据,来渲染detail页面
onLoad: function (options) {
    requests.ajax('GET', 'selectOne', { id: options.projecturl }).then(res => {
      console.log(res)
      this.setData({
        detailDatas: res.data.lftComplaints // detail.wxml中就可对detailDatas进行循环取值渲染页面了
      })
    }) 

先总结这么多吧,后面还有进一步理解的地方会再更~

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值