微信小程序 - 常用API

微信小程序常用API

发起请求

wx.request

wx.request发起的是 HTTPS 请求。一个微信小程序,同时只能有5个网络请求连接。

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json'
  },
  success: function(res) {
    console.log(res.data)
  }
})

 

上传、下载

wx.uploadFile

将本地资源上传到开发者服务器。如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

wx.downloadFile

下载文件资源到本地。客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。

wx.downloadFile({
  url: 'http://example.com/audio/123', //仅为示例,并非真实的资源
  success: function(res) {
    wx.playVoice({
      filePath: res.tempFilePath
    })
  }
})

注:文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,在小程序下次启动时才能访问得到。

本地缓存

wx.setStorage({
  key:"key"
  data:"value"
})

wx.getStorage({
  key: 'key',
  success: function(res) {
    console.log(res.data)
  } 
})

wx.removeStorage({
  key: 'key',
  success: function(res) {
    console.log(res.data)
  } 
})

wx.clearStorage()

 

显示、隐藏消息提示框

wx.showToast({
  title: '加载中',
  icon: 'loading',
  duration: 10000
})

setTimeout(function(){
  wx.hideToast()
},2000)

动态设置当前页面标题

wx.setNavigationBarTitle({
  title: '当前页面'
}) 

导航

wx.navigateTo({
  url: 'test?id=1' // 保留当前页面,跳转到应用内的某个页面
})

  

wx.redirectTo({
  url: 'test?id=1' // 关闭当前页面,跳转到应用内的某个页面
})
 

获取用户信息(需先调用登录接口)

wx.getUserInfo({
  success: function(res) {
    var userInfo = res.userInfo
    var nickName = userInfo.nickName
    var avatarUrl = userInfo.avatarUrl
    var gender = userInfo.gender
    var province = userInfo.province
    var city = userInfo.city
    var country = userInfo.country
  }
})

获取网络类型

wx.getNetworkType({
  success: function(res) {
    var networkType = res.networkType // 返回网络类型2g,3g,4g,wifi
  }
})

获取系统信息

wx.getSystemInfo({
  success: function(res) {
    console.log(res.model)
    console.log(res.pixelRatio)
    console.log(res.windowWidth)
    console.log(res.windowHeight)
    console.log(res.language)
    console.log(res.version)
  }
})

  

获取当前地理位置

wx.getLocation({
  type: 'wgs84',
  success: function(res) {
    var latitude = res.latitude
    var longitude = res.longitude
    var speed = res.speed
    var accuracy = res.accuracy
  }
})

拨打电话

wx.makePhoneCall({
  phoneNumber: '1340000' //仅为示例,并非真实的电话号码
})

  

猜你喜欢

转载自hellolove.iteye.com/blog/2340075