第六章总结

6.1网络API

6.1.1发起网络请求

获取HTML数据

.xml

<buttontype="primary"bindtap="getbaidutap">获取数据</button>
<textareavalue='{{html}}'auto-heightmaxlength='0'></textareavalue>

js

Page({
  data:{
    html:""
  },
  getbaidutap:function(){
    var that = this;
    wx.request({
      url:'https://www.baidu.com',
      data:{},
      header:{'Content-Type':'application/json'},
      success:function(res){
        console.log(res);
        that.setData({
          html:res.data
        })
      }
    })
  }
})

通过wx.request(Object)的GET方法获取邮政编码对应的地址信息

.xml

<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder='6位邮政编码'/>
<button type="primary" bindtap="find">查询</button>
<block wx:for="{{address}}">
    <block wx:for="{{item}}">
        <text>{{item}}</text>
    </block>
</block>

js

Page({
  data:{
    postcode:"",
    address:[],
    errMsg:"",
    error_code:-1
  },
  input:function(e){
    this.setData({
      postcode:e.detail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.data.postcode;
    if(postcode!=null&&postcode!=""){
      var self=this;
      wx.showToast({
        title:'正在查询, 请稍等......',
        icon:'loading',
        duration:10000
      });
      wx.request({
        url:'https://v.juhe.cn/postcode/query',
        data:{
          'postcode':postcode,
          'key':'0ff9bfccdf147476e067de994eb5496'
        },
        header:{
          'Content-Tppe':'application/json',
        },
        method:'GET',
        success:function(res){
          wx.hideToast();
          if(res.data.error_code==0){
            console.log(res);
            self.setData({
              errMsg:"",
              error_code:res.data.error_code,
              address:res.data.result.list
            })
          }
          else{
            self.setData({
              errMsg:res.data.reason || res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
})

6.1.2上传文件

 图片上传到服务器并显示示例代码

.xml

<button type="primary" bindtap="uploadimage">上传图片</button>
<image src="{{img}}" mode="widthFix"/>

js

Page({
  data:{
    img:null,
  },
  uploadimage:function(){
var that=this;
wx.chooseImage({
  success:function(res){
    var tempFilePaths=res.tempFilePaths
    upload(that.tempFilePaths);
  }
})
function upload(page,path){
  wx.showToast({
    icon:"loading",
    title:"正在上传"
  }),
  wx.uploadFile({
    url:"http://localhost/",
    filePath:path[0],
    success:function(res){
      console.log(res);
      if(res.statusCode!=200){
        wx.showModal({
          title:'提示',
          content:'上传失败',
          showCancel:false
        })
        return;
      }
      var data=res.data
      page.setData({
        img:path[0]
      })
    },
    fail:function(e){
      console.log(e);
      wx.showModal({
        title: '提示',
        content: '上传失败',
        showCancel:false
      })
    },
    complete:function(){
      wx.hideToast();
    }
  })
}
  }
})

6.2多媒体API

6.2.1 图片API

wx.chooseImage({
count:2,
sizeType:['original','compressed'],
sourceType:['albnm','camera'],
success:function(res){
var tempFilePaths
var tempFiles=res.tempFiiles;
comsole.log(tempFilePaths)
console.log(tempFiles)
}})
2.预览图片
wx.previewImage({
current:"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
urls:[""],
"http://",
"http://......"]})
 
 
 
 

 3.获取图片信息

wx.chooseImage({
success:function(res){
wx.getImageInfo({
src:res.tempFilePaths[0],
success:function(e){
console.log(r.width)
comsole.log(e.height)
}
})
},
})

 4.保存图片到系统相册

wx.chooseImage({
success:function(res){
wx.saveImageToPhotosAlbum({
filePath:res.tempFilePaths[0],
success:function.log(e)
}
})
},
})

6.2.2录音API

1.开始录音

wx.startRecord接口用于开始录音

2.停止录音

wx.stopRecord接口用于实现主动调用停止录音 

示例代码

wx.startRecord)
({
success:function(res){
var tempFilePath=res.tempFilePath
},
fail:function(res){
}
})
setTimeout(function(){
wx.stopRecord()},10000)

6.2.3 音频播放控制API 

1.播放语音

wx.playVoice接口用于开始播放语言,同时只允许一个语言文件播放,其参数如下

2.暂停播放

wx.pauseVoice用于暂停正在播放的录音.再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放.如果想从头开始播放,则需要先调用wx.stopVoice.

示例代码如下:

wx.startReacord({
success:function(res){
var tempFilePath=res.tempFilePath
wx.playVoice({
filePath:tempFilePath})
setTimeout(function(){
wx.pauseVoice()},5000)}})

6.3 文件API

从网络上下载或录音的文件都是临时保存的,若要持久保存,需要用到文件API。文件
API提供了打开、保存、删除等操作本地文件的能力,主要包括以下5个API接口:
(1)wx.saveFile(Object)接口 用于保存文件到本地。
(2)wx.getSavedFileList(Object)接口 用于获取本地已保存的文件列表。
(3)wx.getSaveFileInfo(Object)接口 用于获取本地文件的文件信息。
(4)wx.removeSaveFile(Object)接口 用于删除本地存储的文件。
(5)wx.openDocument(Object)接口 用于新开页面打开文档,支持格式:doc、xls、 2. 获取ppt、pdf、docx、xlsx、ppts。

1. 保存文件

wx.saveFile(Object)用于保存文件到本地,其相关参数如表6-14所示。

saveImg:function(){
wx.chooseImage({
count:1,//默认值为9
sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认二者都有
sourceType:['album', 'camera'],//可以指定来源是相册还是相机,默认二者都有
success:function(res){
var tempFilePaths = res.tempFilePaths[0]
wx.saveFile({
tempFilePath: tempFilePaths, 
success:function(res){
var saveFilePath = res. savedFilePath;
console. log(saveFilePath)
}
})
}
})
}

2.获取本地文件列表

wx.getSavedFileList(Object)接口用于获取本地已保存的文件列表,如果调用成功,则返回文件的本地路径、文件大小和文件保存时的时间戳(从1970/01/0108:00:00到当前时间的秒数)文件列表。其相关参数如表6-15所示。

wx.getSavedFileList({
success:function(res){
that. setData({
fileList:res.fileList
})
}
})

3.获取本地文件的文件信息

wx.getSaveFileInfo(Object)接口用于获取本地文件的文件信息,此接口只能用于获取已保存到本地的文件,若需要获取临时文件信息,则使用 wx.getFileInfo(Object)接口。其相关参数如表6-16所示。

 

wx.chooseImage({
count:1,//默认值为9 
sizeType:['original''compressed'],//可以指定是原图还是压缩图,默让 if(res.fileList.
二者都有 
sourceType:['album'.'camera'],//可以指定来源是相册还是相机,默认二者都有
success:function(res){
var tempFilePaths = res.tempFilePaths[0]
wx.saveFile({
tempFilePath: tempFilePaths, 
success:function(res){
var saveFilePath = res. savedFilePath;
wx.getSavedFileInfo({
filePath: saveFilePath,
success:function(res){
console.log(res.size
}
})
}
})
}
})

4.删除本地文件

wx.removeSaveFile(Object)接口用于删除本地存储的文件,其相关参数如表6-17所示

wx.getSavedFileList({
success:function(res){
if(res,fileList.length>0){
wx.removeSavedFile({
filePath: res. fileList[0l. filePath, 
complete:function(res){
console.log(res)
}
})
}
}
})

5.打开文档

wx.openDocument(Object)接口用于新开页面打开文档,支持格式有doc,xls,ppt,pdf,docx,xlsx,pptx.其相关参数如表6-18所示

wx.downloadFile({
url:"http://localhost/fm2.pdf",//在本地通过wxamp 搭建服务器
success:function(res){
var tempFilePath =res.tempFilePath;
wx.openDocument({
filePath: tempFilePath,
success:function(res){
console.log("打开成功")
}
})
}
})

6.4本地数据及缓存API

6.4.1 保存数据

1.wx.setStorage

wx.setStorage接口将数据存储到本地缓存接口的指定key中,接口执行后会覆盖原来key对应的内容.其参数如下所示

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

2.wx.setStoragSyne(key,data)

wx.setStorageSync(key,data)是同步接口,其参数只有key和data

wx.setStorageSync('age','25')

6.4.2 获取数据

1.wx.getStorage

wx.getStorage接口是从本地缓存中异步获取指定的key对应的内容,其相关参数如下

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

2.wx.getStorageSync(key)

wx.getStorageSync从本地缓存中同步获取指定key对应的内容,其参数只有key

try{
var value=wx.getStorageSync('age')
if(value){
console.log("获取成功"+value)
}
}catch(e){
console.log("获取失败")
}

6.4.3 删除数据

1.wx.removeStorage

wx.removeStorage接口用于从本地缓存中异步移除指定key,其相关参数如图

wx.removeStorage({
key:'name',
success:function(res){
console.log("删除成功")
},
fail:function(){
console.log("删除失败")
}
})

2.wx.removeStorageSync

wx.removeSync接口用于从本地缓存中同步删除指定key对应的内容,其参数只有key

try{
wx.removeStorageSync('name')
} catch(e){
}

 

6.4.4清空数据

1.wx.clearStorage()

wx.clearStorage()接口用于异步清理本地缓存数据,没有参数

wx.getStorage({
key:'name',
success:function(res){
wx.clearStorage()
},
})

 

2.wx.clearStroageSync()

用于同步清理本地数据缓存

try{
wx.clearStoroageSync()
} catch(e){
}

6.5 位置信息API

6.5.1 获取位置信息

wx.getLocation接口用于获取当前用户的地理位置`速度,需要用户开启定位功能,当用户离开小程序后,无法获取当前位置的地理位置及速度,当用户点击"显示在聊天顶部"时,可以获取到定位信息,其参数如下

 js

wx.getLocation({
type:'wgs85',
success:function(res){
console.log("经度:"+res.longitude);
console.log("纬度:"+res.latitude);
},
})

wxml

<view class="container">
  <view class="button-container">
    <button bindtap="getLocation">获取地理位置信息</button>
  </view>
</view>

 

 

6.5.2 选择位置信息

wx.chooseLocation接口用于在打开的地图中选择位置,用户选择位置后可返回当前位置的名称`地址`经纬度信息,其相关参数如图所示

wx.chooseLocation调用成功后,返回的参数如图所示 js

Page({
  data: {
    markers: [],
    polyline: [],
    controls: []
  },
  onLoad: function () {
    // 在页面加载时调用chooseLocation接口
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        // 更新data中的markers信息,添加选择的位置
        var newMarkers = [{
          iconPath: "../image/选择位置.png",
          id: 0,
          longitude: res.longitude,
          latitude: res.latitude,
          width: 50,
          height: 50
        }];
        this.setData({
          markers: newMarkers
        });
      }.bind(this) // 注意这里使用bind(this),以便在回调函数中使用setData更新data
    });
  },
  regionchange: function (e) {
    console.log(e.type);
  },
  markertap: function (e) {
    console.log(e.markerId);
  },
  controltap: function (e) {
    console.log(e.controlId);
  }
});

wxml

<map id="map"
longitude="108.9200"
latitude="34.1550"
scale="14"
controls="{{controls}}"
bindcontroltap="controltap"
markers="{{markers}}"
bindmarkertap="markertap"
polyline="{{polyline}}"
bindregionchange="regionchange"
show-location
style="width: 100%;height: 300px;"></map>
 

 

6.5.3 显示位置信息

wx.openLocation接口用于在微信内置地图中显示位置信息,其相关参数如表

 wxml

<map id="map" longitude="108.9200" latitude="34.1550" scale="14" controls="{{controls}}" bindcontroltap="controltap" markers="{{markers}}" bindmarkertap="markertap" polyline="{{polyline}}" bindregionchange="regionchange" show-location style="width: 100%; height: 300px;"></map>

js

Page({
  data: {
    locationInfo: {} // 存储位置信息
  },
  onLoad: function () {
    wx.getLocation({
      type:'gcj02',
      success:function(res){
      var latitiud=res.latitiud
      var longitude=res.longitude
      wx.openLocation({
      latitude:latitude,
      longitude:longitude,
      scale:10,
      name:'智慧国际酒店',
      address:'西安市长安区300号'
      })
      }
      })
    // 在页面加载时调用chooseLocation接口
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        // 存储位置信息
        this.setData({
          locationInfo: res
        });
        // 打开地图显示位置信息
        wx.openLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          name: res.name,
          address: res.address
        });
      }.bind(this) // 注意这里使用bind(this),以便在回调函数中使用setData更新data
    });
  },
  regionchange: function (e) {
    // 处理地图区域变化事件
    console.log(e.type);
  },
  markertap: function (e) {
    // 处理点击标记点事件
    console.log(e.markerId);
  },
  controltap: function (e) {
    // 处理点击控件事件
    console.log(e.controlId);
  }
});

6.6  设备相关API

6.6.1 获取系统信息

wx.getSystemInfo接口,wx.getSystemInfoSync接口分别用于异步和同步系统获取系统信息,其相关参数如下

wx.getSystemIfon接口或wx.SystemInfo接口调用成功后,返回系统相关信息,如表所示

js

Page({
  onLoad: function () {
    wx.getSystemInfo({
      success: function (res) {
        console.log("手机型号:" + res.model)
        console.log("设备像素比:" + res.pixelRatio)
        console.log("窗口的宽度:" + res.windowWidth)
        console.log("窗口的高度:" + res.windowHeight)
        console.log("微信的版本号:" + res.version)
        console.log("操作系统版本:" + res.system)
        console.log("客户端平台:" + res.platform)
      }
    })
  }
})

 

6.6.2 网络状态

1.获取网络状态

wx. getNetworkType用于获取网络类型,其相关参数如表所示

如果接口调用成功,则返回网络类型

wx.getNetworkType({
success:function(res){
console.log(res.networkType)
},
})

2.获取网络状态变化

wx.onNetworkStatusChange(CallBack)接口用于监听网络状态变化,当网络状态变化时.返回当前网络状态类型及是否有网络连接

wx.onNetworkStatusChange(function(res){
console.log("网络是否连接:"+res.isConnected)
console.log("变化后的网络类型:"+res.networkType)
})

 

6.6.3 拨打电话

wx.makePloneCall接口用于实现调用手机拨打电话,其相关参数如下

wx.makePhoneCall({
phoneNumber:'1341422234"
})

 

6.6.4 扫描二维码

wx.scanCode接口用于调取客户端扫码界面,扫码成功后返回相应的内容,其相关参数如下

扫码成功后,返回的数据如表所示

wx.scanCode({
success:(res)=>{
console.log(res.result)
console.log(res.scanType)
console.log(res.charSet)
console.log(res.path)
}
})
wx.scanCode({
onlyFromCamera:true,
success:(res)=>{
console.log(res)
}
})

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值