微信小程序的网络请求:微信小程序教程系列14

た 入场券 2021-12-04 09:34 590阅读 0赞

网络请求,基本上是必须的环节之一。

小程序提供了wx.request(object),与开发者的服务器实现数据交互的一个很重要的api。

20170213165746581

最简单的用法如下(以GET请求为例)

  1. <view bindtap="bindSearchChange"><view>
  2. bindSearchChange:function(){
  3. wx.request({
  4. method:"GET", //注意请求方式必须要大写!!!
  5. url:'xxxxxxxxx',
  6. data:{},
  7. header: {'content-type': 'application/json'}, //content-type必须要小写!!!
  8. success: function(res) {
  9. console.log(res)
  10. }
  11. })
  12. }

完整示例:
下面我们把请求写在service文件下的http.js文件中,代码如下

  1. var root = 'hxxxxx';//你的域名
  2. function req(url,data,cb){
  3. wx.request({
  4. url: root + url,
  5. data: data,
  6. method: 'POST',
  7. header: {'content-type': 'application/json'},
  8. success: function(res){
  9. return typeof cb == "function" && cb(res.data)
  10. },
  11. fail: function(){
  12. return typeof cb == "function" && cb(false)
  13. }
  14. })
  15. }
  16. module.exports = { req: req }

其中module.exports是将req方法暴露出去使得别的文件中可以使用该方法,由于js函数是异步执行的,所以return 的是回调函数,而不是具体的数据

为了其他文件方便调用此方法,我们在根目录的app.js文件中将其注册成为全局函数,如下

  1. //app.js
  2. var http = require('service/http.js')
  3. App({
  4. onLaunch: function () {
  5. //dosomething
  6. },
  7. func:{
  8. req:http.req
  9. }
  10. })

这时这个req就是全局的了,在调用时我们可以使用getApp.func.req()来调用,具体如下

  1. var app = getApp()
  2. Page({
  3. data: {
  4. },
  5. onLoad: function (opt) {
  6. app.func.req('/api/get_data',{},function(res){
  7. console.log(res)
  8. });
  9. }
  10. })

目前,小程序还有待完善

其中在网络请求上,还需要注意一些细节:

1> method请求方式,必须要使用大写的GET或POST!!

2> content-type,必须要使用小写,使用大写不能正常发起请求!!

发表评论

表情:
评论列表 (有 0 条评论,590人围观)

还没有评论,来说两句吧...

相关阅读