第六章 总结

网络API

网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。

发起网络请求

示例代码如下:

//index.wxml
 <button type="primary" bindtap="getbaidutap">获取HTML数据</button>
<textarea value="{{html}}" auto-height maxlength="0"></textarea> 

//index.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方法获取邮政编码对应的地址信息

示例代码如下:

//index.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>

//index.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:1000
      });
      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.reason||res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
})

运行结果如下:

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

示例代码如下:
 

//index.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>

//index.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:1000
      });
      wx.request({
        url: 'https://v.juhe.cn/postcode/query',
        data:{
          "postcode":postcode,
          "key":"0ff9bfccdf147476e067de994eb5496e"
        },
        header:{
          "Content-Type":"application/x-www-form-urlencoded",
        },
         method:"POST",
        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
            })
          }
        }
      })
    }
  }
})

运行结果如下:

上传文件

示例代码如下:
 

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

//index.js
Page({
    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({
        filePath: 'path[0]',
        name: 'file',
        url: 'http://localhost/',
        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();
        }
      })
    }
  }
})

运行结果如下:

下载文件

示例代码如下:

//index.wxml
<button type="primary" bindtap="downloadimage">下载图像</button>
<image src="{{img}}" mode="widthFix" style="width: 90%; height: 500px;"></image>

//index.js
Page({
    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
        })
      }
    })
  }
})

运行结果如下:

多媒体API

多媒体API主要包括图片API、录音API、音频播放控制API、音乐播放控制API等,其目的是丰富小程序的页面功能。

图片API
1.选择图片或拍照

wx.chooseImage(Object)接口用于从本地相册选择图片或使用相机拍照。拍照时产生的临时路径在小程序本次启动期间可以正常使用,若要持久保存,则需要调用wx.saveFile保存图片到本地。

示例代码如下:

wz.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)
  }
})
2.预览图片

wx.previewImage(Object)接口主要用于预览图片

示例代码如下:

wx.previewImage({
  current:"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
  urls: ["http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/1.png","http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png","http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/3.png"]
})
3.获取图片信息

wx.getImageInfo(Object)接口用于获取图片信息

示例代码如下:

wx.chooseImage({
  success:function(res){
    wx.getImageInfo({
      src: res.tempFilePaths[0],
      success:function(e){
        console.log(e.width)
        console.log(e.height)
      }
    })
  }
})
4.保存图片到系统相册

wx.saveImageToPhotosAIbum(Object)接口用于保存图片到系统相册,需要得到用户授权scope.writePhotosAIbum

示例代码如下:

wx.chooseImage({
  success:function(res){
    wx.saveImageToPhotosAlbum({
      filePath: res.tempFilePaths[0],
      success:function(e){
        console.log(e)
      }
    })
  }
})
录音API
1.开始录音

wx.startRecord(Object)接口用于实现开始录音

2.停止录音

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

示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
  },
  fail:function(res){
    //录音失败
  }
})
setTimeout(function(){
  //结束录音
  wx.stopRecord()
},10000)
音频播放控制API
1.播放语音

wx.playVoice(Object)接口用于开始播放语音

示例代码如下:

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

      }
    })
  }
})
2.暂停播放

wx.pauseVoice(Object)用于暂停正在播放的语音

示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath: tempFilePath,
    })
    setTimeout(function(){
      //暂停播放
      wx.pauseVoice()
    },5000)
  }
})
3.结束播放

wx.stopVoice(Object)用于结束播放语音

示例代码如下:

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath: tempFilePath,
    })
    setTimeout(function(){
      wx.stopVoice()
    },5000)
  }
})
音乐播放控制API
1.播放音乐

wx.playBackgroundAudio(Object)用于播放音乐

2.获取音乐播放状态

wx.getBackgroundAudioPlayerState(Object)接口用于获取音乐播放状态

接口调用成功后返回的参数如下表:

3.控制音乐播放进度

wx.seekBackgroundAydio(Object)接口用于控制音乐播放进度

4.暂停播放音乐

wx.pauseBackgroundAudio()接口用于暂停播放音乐

5.停止播放音乐

wx.stopBackgroundAudio()接口用于停止播放音乐

6.监听音乐播放

wx.onBackgroundAudioPlay(CallBack)接口用于实现监听音乐播放

7.监听音乐暂停

wx.onBackgroundAudioPause(CallBack)接口用于实现监听音乐暂停

8.监听音乐停止

wx.onBackgroundAudioStop(CallBack)接口用于实现监听音乐停止

9.案例展示

示例代码如下:

//index.wxml
<view class="container">
<image class="bgaudio" src="{{changedImg?music.coverImg:'/images/img_01.jpg'}}" />
<view class="control-view">
<image src="/images/img_02.jpg" bindtap="onPositionTap" data-how="0" />
<image src="/images/{{isPlaying?'img_01':'img_02'}}.jpg" bindtap="onAudioTap" />
<image src="/images/img_03.jpg" bindtap="onStopTap"/>
<image src="/images/img_04.jpg" bindtap="onPositionTap" data-how="1"/>
</view>
</view>

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


//index.json
{}


//index.js
Page({
  data:{
   isPlaying:false,
   changedImg:false,
   music:{ "url":"http://m10.music.126.net/20240327195053/f471ce2da86fa5e2ffea2fef033e81f9/ymusic/9be4/2eb8/0495/171f720ebce523154af8c38f6cc36099.mp3",
      "title":"盛晓梅 -有一天",
      "coverImg":"/images/pic01.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");
    });
  }
})

运行结果如下:

文件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:tempFilePaths,
         success:function(res){
           var saveFilePath=res.saveFilePath;
           console.log(saveFilePath)
        }
      })
    }
   })
}
2.获取本地文件列表

示例代码如下:

wx.getSavedFileList({
  success:function(res){
    that.setData({
      fileList:res.fileList
    })
  }
})
3.获取本地文件的文件信息

示例代码如下:

wx.chooseImage({
  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.saveFilePath;
            wx.getSavedFileInfo({
              filePath:saveFilePath,
              success:function(res){
                console.log(res.size)
              }
            })
          }
        })
      }
    })
4.删除本地文件

示例代码如下:

wx.getSavedFileList({
  success:function(res){
    if(res.fileList.length>0){
      wx.removeSavedFile({
        filePath:res.fileList[0].filePath,
        complete:function(res){
          console.log(res)
        }
      })
    }
  }
})
5.打开文档

示例代码如下:

wx.downloadFile({
  url: 'http://localhost/fm2.pdf',
  success:function(res){
    var tempFilePath=res.tempFilePath;
    wx.openDocument({
      filePath: tempFilePath,
      success:function(res){
        console.log("打开成功")
      }
    })
  }
})

本地数据及缓存API

小程序提供了以键值对的形式进行本地数据缓存功能,并且是永久存储的,但最大不超过10MB,其目的是提高加载速度。

1.保存数据

1.wx.setStorage(Object)

示例代码如下:

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

2.wx.setStorageSync(key,data)

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

示例代码如下:

wx.setStorageSync('age', '25')
2.获取数据

1.wx.getStorage(Object)

示例代码如下:

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

2.wx.getStorageSync(key)

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

示例代码如下:

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

1.wx.removeStorage(Object)

示例代码如下:

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

2.wx.removeStorageSync(key)

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

示例代码如下:

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

}
4.清空数据

1.wx.clearStorage()

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

示例代码如下:

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

2.wx.clearStorageSync()

wx.clearStorageSync()接口用于同步清理本地数据缓存。

示例代码如下:

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

}

位置信息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号'
    })
  }
})

设备相关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(Object)用于获取网络类型

示例代码如下:

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

wx.onNetworkStatusChange(CallBack)接口用于监听网络状态变化

示例代码如下:

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

示例代码如下:

wx.makePhoneCall({
  phoneNumber: '12345678910',
})
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)
  }
})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值