小程序学习--4

小程序学习–4 API

说明

基本参照官方文档

简介

框架提供丰富的微信原生API,可以方便使用微信提供的能力,如获取用户信息,本地存储,支付能力等

  • wx.on 开头的API 是监听某个事件发生的API接口,接受一个callback 函数作为参数,当该事件触发时,会调用callback函数
  • 如没有特殊约定,其他API接口都接受一个Object对象作为参数
  • Object中可以指定success、fail、complete 来接受接口调用结果

API

发起请求 wx.request({})

wx.request 发起的是HTTPS请求

    wx.request({
      url:'http://www.baidu.com',   // 服务器接口地址
      data: {                       // 请求的参数

      },
      header: {                     // 设置请求的 header , header 中不能设置 Referer
        'Content-Type': 'application/json'
      },
      method: 'GET',                // 设置请求类型,默认GET
      dataType: 'json',             // 默认值json
      success: function (res) {     // 服务器响应成功的回调
        console.log(res);
      },
      fail: function () {           // 接口调用失败的回调

      },
      complete: function () {       // 接口调用结束的回调(成功失败都会执行)

      }
    })
图片选择与调用微信拍照 wx.chooseImage({})
    let that = this;
    wx.chooseImage({
      count: 4,                             // 最多可以选择的图片张数,默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'],      // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 成功,返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths // 获得选中图片临时路径列表,下次载入小程序无法使用
        console.log(res);
        that.setData({avatarUrl: tempFilePaths[0]});
      }
    })
资源上传 wx.uploadFile({})
    wx.chooseImage({
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'http://example.weixin.qq.com/upload', // 服务器地址,用来上传的地址
          filePath: tempFilePaths[0],                 // 要上传文件资源的路径
          name: 'file',                               // 文件对应的key
          header: {                                   // HTTP 请求 Header , header 中不能设置 Referer
          },
          formData:{                                  // HTTP请求中其他额外的formdata
            'user': 'test'
          },
          success: function(res){                     // 成功后回调
            var data = res.data
            console.log(data);
            //do something
          },
          fail: function () {                         // 失败后回调
            console.log('error');
          },
          complete: function () {                     // 接口调用结束后后回调
            console.log('complete');
          }
        })
      }
    })
资源下载 wx.downloadFile({})
    wx.downloadFile({
      url: 'http://img02.tooopen.com/images/20150201/sl_109935941543.jpg',
      header:{
      },
      success: function (res) {
        console.log(res.tempFilePath);
      },
      fail: function () {
        console.log('error');
      },
      complete: function () {
        console.log('complete');
      }
    })
WebSocket

一个微信小程序同时只能有一个WebSocket链接,如果当前存在一个WebSocket 链接,会自动关闭该链接,并重新创建一个 WebSocket链接

wx.connectSocket({})

建立链接

    wx.connectSocket({
      url: 'test.php',          // 服务器接口地址
      data: {},                 // 请求携带数据
      header: {},               // 请求的header
      method: 'GET',            // 请求的方式
      success: function (res) { // 成功回调
        console.log(res);
      },
      fail: function () {       // 失败回调
        console.log('error');
      },
      complete: function () {   // 结束回调
        console.log('complete');
      }
    })
wx.sendSocketMessage({})

通过 WebSocket 链接发送数据,需要在链接建立之后并且在 wx.onSocketOpen 回调之后才能发送

    wx.connectSocket({
      url: 'test.php',
      success: function () {}
    })
    wx.onSocketOpen(function () {     // WebSocket 链接开启之后
     wx.sendSocketMessage({           // 发送数据
       data: 'this is new message',   // 发送的内容(string/Array)
       success: function () {},       
       fail: function () {},
       complete: function () {}
     })
   })
wx.closeSocket({})

关闭 WebSocket 链接

wx.onSocketOpen(fn)

监听 WebSocket 打开事件

    wx.onSocketOpen(function (res) {
      console.log(res);
    })
wx.onSocketError(fn)

监听 WebSocket 报错

    wx.onSocketError(function (res) {
      console.log(res);
    })
wx.onSocketMessage(fn)

监听 WebSocket 接受到服务器的消息事件

    wx.onSocketMessage(function (msg) {
      console.log(msg.data);
    })
wx.onSocketClose(fn)

监听WebSocket关闭。

注意:必须在 WebSocket 开启期间 调用才能关闭

文件
wx.saveFile({})

保存文件到本地

wx.getSavedFileList({})

获取本地已保存的文件列表

wx.getSavedFileInfo({})

获取本地文件的文件信息

wx.removeSavedFile({})

删除本地存储的文件

wx.openDocument({})

新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx

  wx.chooseImage({
    success: function(res) {
      console.log(res);
      let tempFilePath = res.tempFilePaths[0];
      wx.saveFile({
        tempFilePath: tempFilePath,
        success: function(res) {
          var savedFilePath = res.savedFilePath
          console.log(savedFilePath);
        }
      })
    }
  })
  wx.getSavedFileList({
    success: function (resp) {
      console.log(resp);
      let path = resp.fileList[0].filePath;
      wx.getSavedFileInfo({
        filePath: path,
        success: function (respo) {
          console.log(respo);
        }
      })
    }
  })
缓存数据

每个微信小程序都可以有自己的本地缓存,小程序提供的接口可以对本地缓存进行设置、获取和清理,本地缓存最大为 10MB

注意: localStorage 是永久存储

  • wx.setStorage({})(异步)\ wx.setStorageSync(KEY,DATA) (同步)

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容

  • wx.getStorage({})(异步)\ wx.getStorageSync(KEY)(同步)

从本地缓存中获取指定 key 对应的内容

  • wx.getStorageInfo({})(异步)\ let res = wx.getStorageInfoSync()(同步)

获取当前storage的相关信息,包括keys 、当前占用空间(currentSize)限制空间大小(limitSize)

  • wx.removeStorage({})(异步)\ wx.removeStorageSync(KEY)(同步)

从本地缓存中移除指定 key

  • wx.clearStorage()(异步)\ wx.clearStorageSync()(同步)

清理本地数据缓存

  add: function () {
    let oldVal = wx.getStorageSync('test') || [];
    oldVal.push(this.data.inputval);
    wx.setStorage({
      key: 'test',
      data: oldVal,
      success: function () {console.log('true')},
      fail: function () {console.log('false')}
    })
  },
  get: function () {
    let that = this;
    wx.getStorage({
      key: 'test',
      success: function (res) {
        console.log(res);
        that.setData({
          msg : res.data
        })
      }
    })
  },
  getinfo: function () {
    wx.getStorageInfo({
      success: function (res) {
        console.log(res.keys);
        console.log(res.currentSize);
        console.log(res.limitSize);
      }
    })
  },
  remove: function () {
    wx.removeStorageSync('test');
    let res = wx.getStorageInfoSync();
    console.log(res);
  },
  clear: function () {
    wx.clearStorage();
    let res = wx.getStorageInfoSync();
    console.log(res);
  },
设备信息
网络状态 wx.getNetworkType({})

获取网络类型

  wx.getNetworkType({
      success: function (res) {
        console.log(res.networkType);
      }
    })
wx.getSystemInfo({})(异步) \ let res = wx.getSystemInfoSync()(同步)

获取系统信息

  wx.getSystemInfo({
      success: function (res) {
        console.log(res);
      }
    })
wx.makePhoneCall({})

拨打电话

    wx.makePhoneCall({
      phoneNumber: '110',
      success: function (res) {
        console.log(res);
      }
    })
wx.scanCode({})

扫码,(编辑器中会调出本地文件夹,返回fail),

    wx.scanCode({
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      }
    })
交互反馈
wx.showToast({}) \ wx.hideToast()

显示\取消消息提示框

  bindViewTap: function() {
    wx.showToast({
      title: 'this is title', // 提示的内容
      icon: 'success',        // 图标,只支持"success"、"loading"
      duration: 3000,         // 提示的延迟时间
      mask: false,            // 是否显示透明蒙层
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  remote: function () {
    wx.hideToast();         // 取消显示
  },
wx.showModal({})

​显示模态弹窗

  wx.showModal({
      title: 'this is title',
      content: 'this is content',
      showCancel: true,
      cancelText: '取消了',
      acancelColor: '#444444',
      confirmText: '确定了',
      confirmColor: '#eee',
      success: function (res) {
        console.log(res.confirm);
      },
      fail: function (res) {
         console.log(res.confirm);
      }
    })
wx.showActionSheet({})

显示操作菜单

  bindViewTap: function() {
    let list = ['this is first', 'this is second', 'this is third'];
    wx.showActionSheet({
      itemList: list,             // 按钮的文字数组,数组长度最大为6个
      itemColor: '#333',          // 按钮的文字颜色
      success: function (res) {   // 接口调用成功的回调函数
        console.log('success');
        console.log(res.tapIndex);
      },
      fail: function (res) {      // 接口调用失败的回调函数
        console.log('fail');      // 在开发工具中如果点击菜单中的取消,先执行fail然后又执行success(不清楚原因)
      }
    })
  },
导航
wx.setNavigationBarTitle({})

动态设置当前页面的标题

wx.showNavigationBarLoading()

显示导航条加载动画

wx.hideNavigationBarLoading()

隐藏导航条加载动画

  bindViewTap: function() {
    wx.setNavigationBarTitle({
      title: 'this is title',
      success: function (res) {
        console.log(res);
        wx.showNavigationBarLoading();
        setTimeout(() => {
          wx.hideNavigationBarLoading();
        }, 1000)
      }
    })
  },
wx.navigateTo({})

保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。

    wx.navigateTo({
      url: '../logs/logs',      // 应用内非 tabBar 的页面的路径,路径后可以带参数,如 'path?key=value&key2=value2'
      success: function (res) {
        console.log(res);
      }
    })
wx.redirectTo({})

关闭当前页面,跳转到应用内的某个页面。

    wx.redirectTo({
      url: '../logs/logs',      // 应用内非 tabBar 的页面的路径,路径后可以带参数
      success: function (res) {
        console.log(res);
      }
    })
wx.switchTab({})

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面

    wx.switchTab({
      url: '../logs/logs',  // tabBar 页面的路径(需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数
      success: function (res) {
        console.log(res);
      }
    })
wx.navigateBack({delta:0})

关闭当前页面,返回上一页面或多级页面。

  wx.navigateBack({
    delta: 2
  })
下拉刷新
onPullDownRefresh:fn \ wx.stopPullDownRefresh()

在 Page 中定义 onPullDownRefresh 处理函数,监听该页面用户下拉刷新事件。

wx.stopPullDownRefresh()停止当前页面下拉刷新。

  onPullDownRefresh: function () {
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000)
  }

注意:需要在app.json 文件中 window 选项下 开启 enablePullDownRefresh

开放接口
wx.login({})

调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)。用户数据的加解密通讯需要依赖会话密钥完成。

  wx.login({
    success: function (resp) {    // 登录成功
      console.log(resp.code);     // 需要将 code 发送到开发者服务器后台,使用code 换取 session_key api,将 code 换成 openid 和 session_key

    }
  })

用户登录比较复杂,详情参考官方文档

wx.checkSession({})

检查登录态是否过期

  wx.checkSession({
    success: function(){
      //登录态未过期
    },
    fail: function(){
      //登录态过期
      wx.login()
    }
  })
wx.getUserInfo({})

获取用户信息,需要先调用 wx.login 接口

  wx.login({
    success: function (resp) {
      console.log(resp);
      wx.getUserInfo({
        success: function (res) {
          console.log(res);
          that.globalData.userInfo = res.userInfo
        }
      })
    }
  })
wx.requestPayment({})

发起微信支付

wx.requestPayment({
   'timeStamp': '',
   'nonceStr': '',
   'package': '',
   'signType': 'MD5',
   'paySign': '',
   'success':function(res){
   },
   'fail':function(res){
   }
})

总结

官方文档提供的接口很多,但是由于本人暂时还没有拿到AppID,所以很多功能测试不了,上边列举的接口,都是一些个人感觉会用到的,以后会结合组件做一些demo。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值