第六章 API应用

6.1  网络API

微信小程序处理的数据通常从后台服务器获取,再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。微信原生API接口或第三方API提供了各类接口实现前后端交互。
网络 API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的
使用等功能处理。微信开发团队提供了10个网络API接口。
wx.request(0bject)接口用于发起 HTTPS 请求。
■wx.uploadFile(Object)接口用于将本地资源上传到后台服务器。
■wx.downloadFile(Object)接口 用于下载文件资源到本地。
■wx.connectSocket(0bject)接口 用于创建一个 WebSocket 连接。
■wx.sendSocketMessage(0bject)接口用于实现通过 WebSocket 连接发送数据。
■wx.closeSocket(0bject)接口 用于关闭 WebSocket 连接。
■wx.onSocketOpen(CallBack)接口用于监听 WebSocket 连接打开事件。
■wx.onSocketError(CallBack)接口 用于监听 WebSocket 错误。
■wx.onSocketMessage(CallBack)接口用于实现监听WebSocket 接收到服务器的消息
事件。

6.1.1 发起网络请求

wx.request 实现向服务器发送请求,获取数据等各种网络交互操作,相关数据如图:

例如,通过 wx.request(0bject)获取百度( https:/ www.baidu.com)首页的数据。(需要在微信公众平台小程序服务器配置中的request 合法域名中添加“https:// www.baidu.com”。)

示例代码:

//wxml
<button type="primary" bindtap="getbaidutap">获取HTML数据</button>
<textarea value='{{html}}' auto-heightmax length='0'></textarea>
//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方法获取邮政编码对应的地址信息。示例代码如下:

//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:'',
   addess:[],
   errMsg:'',
  error_code:-1
  },
  input:function(e){
    this.setDate({
      postcode:e.detail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.date.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':'off9bfccdf147476e067de994eb5496e'
        },
        header:{
          'Content-Type':'application/json',
        },
        method:'GET',
        success:function(res){
          wx.hideToast();
          if(res.data.error_code==0){
            console.log(res);
            self.setDate({
              errMsg:'',
              error_code:res.data.error_code,
              addess:res.data.result.list
            })
          }
          else{
            self.setDate({
              errMsg:res.data.reason||res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
});

运行结果:

例如,通过 wx,request(0bject)的 POST 方法获取邮政编码对应的地址信息

示例代码如下:

//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:'',
   addess:[],
   errMsg:'',
  error_code:-1
  },
  input:function(e){
    this.setDate({
      postcode:e.detail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.date.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':'off9bfccdf147476e067de994eb5496e'
        },
        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.setDate({
              errMsg:'',
              error_code:res.data.error_code,
              addess:res.data.result.list
            })
          }
          else{
            self.setDate({
              errMsg:res.data.reason||res.data.reason,
              error_code:res.data.error_code
            })
          }
        }
      })
    }
  }
});

运行效果如上  

6.1.2 文件的上传

接口用于将本地资源上传到开发者服务器,并且在客户端发一个HTTPS POST请求,相关参数如图:

 通过 wx.uploadFile(0bject),可以将图片上传到服务器并显示。

示例代码如下;

//wxml
<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(this.tempFilePaths);
      }
    })
    function upload(page,path){
      wx.showToast({
        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();
      }
      })
    }
  }
})

运行结果:

6.1.3 下载文件

wx. downloadFie(0bject)接口用于实现从开发者服务器下载文件资源到本地,在客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。其相关参数如表所示。

 通过 wx.uploadFile(0bject),可以将图片上传到服务器并显示。

示例代码如下;

//wxml
<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(this.tempFilePaths);
      }
    })
    function upload(page,path){
      wx.showToast({
        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();
      }
      })
    }
  }
})

运行结果

6.2  多媒体API

6.2.1 图片API

主要包括以下四个API接口:

1.wx.chooselmage(Object)接口  用于从本地相册选择图片或使用相机拍照。

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

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

//js
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/055/1.png",
"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/055/2.png",
"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/055/3.png"
]
})

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

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

4.wx.saveImageToPhotosAlbum(Object)接口 用于保存图片到系统相册。

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

6.2.2 录像API

主要包括2个API:

1.开始录音

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

2.停止录音  

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

示例代码;

//js
wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
  },
  fail:function(res){
//录音失败
 
  }
  })
   setTimeout(function(){
//结束录音
     wx.stopRecord()
   },10000)

6.2.3 音频播放控制API

包括播放,暂停,停止及audio组件的控制,主要包括以下3个API:

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

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

2.wx.pauseVoice(Object)接口 用于实现暂停正在播放的语音

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

3.wx.stopVoice(Object)接口 用于实现结束播放语音

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

6.2.4 音乐播放控制API

音乐播控制API包括8个API:

1.播放音乐

 2.获取音乐播放状态

  3.控制音乐播放进度

    .........

案例展示:

代码:

//wxml
<view class="container">
<image class="bgaudio" src="{{changedImg? music.coverImg:'/image/background.png'}}"/>
<view class="control-view">
<image src="/image/j4.jpg"bindtap="onPositionTap"data-how="0"/>
<image src="/image/{{isPlaying?'pause':'play'}}.png"bindtap="onAudioTap"/>
<image src="/image/j7.jpg"bindtap="onStopTap"/>
<image src="/image/j8.jpg"bindtap="onPositionTap"data-how="1"/>
</view>
</view>
//js
Page({
  data: {
   isPlaying:false,
   coverImg,
   changedImg:false,
   music:{
     "url":
     "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3",
     "title":"盛晓梅,有一天",
     "coverImg":
     "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/j4.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");
});
  }
})
//wmss
.bgaudio{
  height: 350rpx;
  width: 350rpx;
margin-bottom: 100rpx;
}
.control-viewimage{
  height: 64rpx;
width: 64rpx;
max-width: 30rpx;
}

运行效果图:

6.3  文件API

文件API提供了打开,保存,删除等本地文件能力,主要包括以下5个API接口:

1.保存文件

wx.saveFile(Object)接口     用于保存文件到本地。

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

2.获取本地文件列表

wx.getSavedFileList(Object)接口     用于获取本地文件已保存的文件信息。

代码: 

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

结果;

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

wx.getSaveFileInfo(Object)接口     用于获取本地文件的文件信息。

示例代码:

//js

wx.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','carmera'],
success:function(res){
var tempFilePaths=res.tempFilePaths[0]
success:function(res){
var saveFilePath=res.savedFilePath;
wx.getSavedFilePath,
success:function(res){
console.log(res.size)
})
}
})
}
})

4.删除本地的文件

wx.removeSaveFile(Object)接口     用于删除本地存储的文件。

   

 示例代码:

//js
//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.openDocument(Object)接口     用于新开页面打开文档,支持格式:doc,xls,ppt,pdf,docx,xlsx,ppts。

示例代码:

//js
wx.downloadFile({
url:"file:///C:/Users/%E5%BE%90%E5%86%AC%E5%86%AC/Desktop/%E9%9B%B6%E6%97%B6%E6%96%87%E4%BB%B6%E5%A4%B9/vue.pdf",
  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()

示例代码:

//js

wx.setStorage({

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

2.wx.setStorageSync() 

//js

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

6.4.2 获取数据

1.wx.getStorage()

//js​

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

2.wx.getStorageSync(key)

//js

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

6.4.3 删除数据

1  wx.removeStorage

//js

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

  })

2.wx.removeStorageSync(key)

//js


try{
wx.removeStorageSync(key)
}catch(e){
  //Do something whencatch error
}

6.4.4 清空数据

1 wx.clearStorage

//js

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

 2.wx.clearStorageSync

//js

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

6.5 位置信息API

6.5.1 获取位置信息

wx.getLocation(object)接口,获取位置信息,相关参数如下:

wx.getLocation(object)成功返回相关信息 :

示例代码: 

//js

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

运行效果:

6.5.2 选择位置信息

wx.chooseLocation(object)接口,用于选择位置信息,相关信息:

 wx.chooseLocation(object)成功返回相关信息 :

//js

wx.chooseLocation({
    success:function(res){
      console.log("位置的名称"+res.longitude)
      console.log("位置的地址"+res.accuracy)
      console.log("位置的纬度"+res.horizontalAccuracy)
      console.log("位置的纬度"+res.verticalAccuracy)
    }
})

运行效果:

6.5.3 显示位置信息

wx.openLocation(object)接口,用于显示位置信息,相关信息:

 

//js

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.6 设备相关API 

6.6.1 获取系统信息

1wx.getSystemInfo()接口,wx.getSystemInfoSync()接口分别用于异步和同步获取系统信息。其相关参数:

wx.getSystemInfo()接口,wx.getSystemInfoSync()接口调用成功后,返回系统相关信息:

 

示例代码:

//js

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

运行效果图:

 

6.6.2  网络状态

wx.getNetworkType()用于获取网络类型,其参数如下:

//js

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

 运行效果图:

6.6.3  拨打电话

wx.makePhoneCall()接口实现调用手机打电话,其相关参数如下:

代码:

//js

wx.makePhoneCall({
  phoneNumber: '12339',
})

6.6.4  扫描二维码

wx.scanCode()接口用于调起客户端扫码界面,相关参数如下:

扫码成功后,返回数据

运行代码:

//js

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

效果图:

  • 23
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值