第六章总结

1.网络API

1)发起网络请求

示例代码-1

wxml

<button type="primary" bind:tap="getbaidutap">get HTML</button>
<textarea value='{{html}}' auto-heightmaxlength="0"/>

js

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

    })
  }
})

示例代码-2

wxml

<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':'0ff9bfccdf147476e067de994eb5496e'
  },
  header :{
  'Content-Type ':'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.reasonllres.data.reason,
  error_code:res.data.error_code
  })
  }
  }
  })
  }
  }
  })

运行效果-1

运行效果-2

2)上传文件

示例代码:

wxml

 
<button type="primary"bindtap="uploadimage">上传图片</button ><image src="/images/2.jpg"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){
  //显示toast提示消息
  wx.showToast({
  icon:"loading",
  title:"正在上传"
  }),
  wx.uploadFile({
  url:"http://localhost/",
  filePath:path[0],
  name:'file',
  success:function(res){
  console.log(res);
  if(res.statusCodel=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();
  }
  })
  }
  }
  }
  })

运行效果

3)下载文件

示例代码:

wxml

<button type="primary" bind:tap="downloadimge">下载图像</button>
<image src="{{img}}"mode='widthFix'style = "width:90%;height:500px"></image>

js

Page({
  data:{
    img:null,
  },
  downloadimage:function(){
    var that = this;
    wx.downloadFile({
      url: "http://localhost/1.jpg", 
      success:function(res){
        console.log(res)
        that.setData({
          img:res.tempFilePath
        })
      }
    })
  }
 })

运行效果

2.多媒体API

1)图片API

示例代码

选择图片

 wx.chooseImage({
    count:2,
    sizeType:['original','compressed'],
    sourceType:['album','camera'],
    success:function(res){
    var tempFilePaths =res.tempFilePaths
    var tempFiles =res.tempFiles;
    console.log(tempFilePaths)
    console.log(tempFiles)
    }
    })

预览图片

wx.previewImage(
current: " http://bmob-cdn - 16488.60.upaiyun.com/2018/02/052.png",
urls:["http://bmob-cdn-16488.b0. upaiyun.com/2018/02/05/1.png",
"http://bmob-can-16488.b0.upaiyun.com/2018/02/05/2.png",
"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05 /3.jpg"
]
})

 获取图片

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

保存图片

  

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

2)录音API

示例代码

停止录音

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

3)音频播放控制API

示例代码

播放音频

wx.startRecord({
success: function(res){
var tempFilePath= res.tempFilePath wx.playVoice({
filePath:tempFilePath, complete:function(){
}
})
}
})

暂停播放

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

 结束播放

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

4)音乐播放控制API

示例代码

播放音乐

wx.playBackgroundAudio({
dataUrl:'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/01/ti.mp3',
title:'有一天',
coverImgUrl:'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/01/si.jpg',
success:function(res){
console.log(res)
}
})

获取播放音乐状态

wx.getBackgroundAudioPlayerState({
 success:function(res){
var status=res.status
var dataUrl=res.dataUrl
var currentPosition=res.currentPosition
var duration=res.duration
var downloadPercent=res.downloadPercent
console.log("播放状态:"+status)
console.log("音乐文件地址:"+dataUrl)
console.log("音乐文件当前播放位置:"+currentPosition)
console.log("音乐文件的长度:"+duration)
console.log("音乐文件的下载进度:"+status)
}
})

 控制音乐播放进度

wx.seekBackgroundAudio({
posiyion:30
})

暂停音乐播放

wx.playBackgrondAudio{
dataUrl:'/music/a.mp3',
title:'我的音乐',
coverImgUrl:'/images/poster.jpg',
success:function(){
console.log('开始播放音乐了');
}
});
setTimeout(function(){
console.log('暂停播放');
wx.pauseBackgroundAudio();
},5000);

停止播放

wx.playBackgrondAudio{
dataUrl:'/music/a.mp3',
title:'我的音乐',
coverImgUrl:'/images/poster.jpg',
success:function(){
console.log('开始播放音乐了');
}
});
setTimeout(function(){
console.log('暂停播放');
wx.stopBackgroundAudio();
},5000);

 监听音乐播放

wx.playBackgrondAudio{
dataUrl:'/music/a.mp3',
title:'我的音乐',
coverImgUrl:'/images/poster.jpg',
success:function(){
console.log('开始播放音乐了');
}
});
setTimeout(function(){
console.log('暂停播放');
wx.stopBackgroundAudio();
},5000);

案例

wxml

<view class="container">
<image class="bgaudio"src = "{{changedImg? music.coverImg:'/images/屏幕截图 2024-03-06 194010.png'}}"/>
<view class ="control-view">
<image src ="/images/屏幕截图 2024-03-06 193800.png"bindtap="onPositionTap"data-how= "0 "/>
<image src = "/images/{{isPlaying? 'pause' : 'play'}}.png" bindtap = "onAudioTap"/>
<image src ="/images/屏幕截图 2024-03-06 193809.png"bindtap = "onStopTap"/>
<image src ="/images/屏幕截图 2024-03-06 194000.png"bindtap ="onPositionTap"data-how = "1"/>
</view >
</view >

js

Page({
  data:{
  isPlaying:false,
  coverImgchangedImg:false,	
  music:{
  "url":"/music/ヰ世界情緒 - 鳥の詩.mp3",
  "title":"盛晓玫-有一天",
  "coverImg":
  "/images/1.jpg"
  	},
  },	
  onLoad:function(){	
  	this.onAudioState();	
  	},	
	onAudioTap:function(event){	
  if(this.data.isPlaying){
  	wx.pauseBackgroundAudio();	
  	}else{	
 let music = this.data.music;
  	wx.playBackgroundAudio({	
  	dataUrl: music.url,	
  	title: music.title,	
  	coverImgUrl:music.coverImg	
    })	
  }
},
	onStopTap:function(){	
   let that = this;
	wx.stopBackgroundAudio({	
	success:function(){	
  that.setData({ isPlaying:false,changedImg:false});
  }
})	
},
	onPositionTap:function(event){	
 let how = event.target.dataset.how;
	wx.getBackgroundAudioPlayerState({	
	success:function(res){	 
let status = res.status;
 if(status === 1){
let duration = res.duration;
let currentPosition = res.currentPosition;
if(how ==="0"){
let position = currentPosition - 10;
if(position <0){
position =1;	
}
wx.seekBackgroundAudio({	
position: position	
});	
wx. showToast({title:"快退10s",duration:500});
}	
if(how === "1"){
let position =currentPosition +10;
if(position >duration){
position =duration-1;	
}
wx.seekBackgroundAudio({	
position: position});
wx.showToast({ title:"快进10s",duration:500});
}	
}else {
wx.showToast({title:"音乐未播放",duration:800});	
  }	
}
})
},	
onAudioState:function(){	
let that =this;
wx.onBackgroundAudioPlay(function(){
that.setData({ isPlaying:true,changedImg:true});	
console.log("on play");	
});	
wx.onBackgroundAudioPause(function(){	
that.setData({isPlaying:false});
console.log("on pause");	
});	
wx.onBackgroundAudioStop(function(){	
that.setData({isPlaying:false,changedImg:false});	
console.log("on stop");	
});	
}
})

wxss

.bgaudio{
  height:350rpx; width:350rpx;
  margin-bottom:100rpx;
}
  .control-view image{ 
  height:64rpx;
     width:64rpx; 
     margin:30rpx;
}

运行效果

3.文件API

1)保存文件

示例代码

saveImg:function()
wx.chooseImage(
count:1,
sizeType:[original',compressed'],
sourceType:[album,camera],
success;function(res)var tempFilePaths = res.tempFilePaths[0]
wx.saveFile(!tempFilePath:tempFilePath
ssuccess:function(res)
varsaveFilePath=res.savedFilePath;
console.log(saveFilePath)
}
})
}
})
}

2)获取本地文件列表

示例代码

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

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

示例代码

wx.chooseImage(1
count:1,
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;
wx.getSavedFileInfo(!
filePath:saveFilePath,
success:function(res)
console.log(res.size)
}
})
}
})
}
})

4)删除文件

示例代码

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

5)打开文档

示例代码

wx.downloadFile(i
url:"http://localhost /fm2.pdf",
success:function(res)
var tempFilePath =res. tempFilePath;
wx.openDocument(
filePath: tempFilePath,success:function(res)console.1og(“打开成功”)
}
})
}
})

4.本地数据及缓存API

1)保存数据

 代码:

异步接口

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

 同步接口

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

2)获取数据

 代码:

异步

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

同步

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

3)删除数据

 代码:

object

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

 key

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

4)清空数据

 代码:

异步

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

同步

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

5.位置信息API

1)获取位置信息

 代码:

wx.getLocation({
  type:'wgs84',
  success:function(res){
console.log("经度:"+res.longitude);
console.log("纬度:"+res.latitude);
console.log("速度:"+res.longitude);
console.log("位置的精确度:"+res.accuracy);
console.log("水平精确度:"+res.horizontalAccuracy);
console.log("垂直精确度:"+res.verticalAccuracy);
  },
})

2)选择位置信息

 代码:

 wx.chooseLocation({
  success:function(res){
console.log("位置的名称:"+res.name)
console.log("位置的地址:"+res.address);
console.log("位置的经度:"+res.longitude);
console.log("位置的纬度:"+res.latitude)
  }
})

3)显示位置信息

 代码:

wx.getLocation({
  type:'gcj02',
  success:function(res){
    var latitude=res.latitude
    var longitude=res.longitude
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale:10,
      name:'智慧国际酒店',
      address:'西安市长安区西长安区300号'
    })
  }
})

6.设备相关API

1)获取系统信息

 代码:

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)
  }
})

运行效果

2)网络状态

代码:

获取网络状态 

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

 监听网络状态

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

3)拨打电话

代码:

wx.makePhoneCall({
phoneNumber:'1145141919810'
})

运行效果

4)扫描二维码

代码:

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)
   }
  })

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值