微信小程序网络请求wx.request请求

最近微信小程序开始开放测试了,小程序提供了很多api,极大的方便了开发者,其中网络请求api是wx.request(object),这是小程序与开发者的服务器实现数据交互的一个很重要的api。 

百牛信息技术bainiu.ltd整理发布于博客园
大家可以先看官方文档微信小程序API 
再给大家提供一个开发工具下载地址小程序开发工具 
最简单的用法如下(以POST请求为例)

bindSearchChange:function(e){  
       var keyword = e.detail.value;  
       wx.request({  
         url:'xxxxxxxxx',  
         data:{},  
         header: {'Content-Type': 'application/json'},  
         success: function(res) {  
           console.log(res)  
         }  
       })  
     }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

 var rootDocment = 'hxxxxx';//你的域名  
    function req(url,data,cb){  
        wx.request({  
          url: rootDocment + url,  
          data: data,  
          method: 'post',  
          header: {'Content-Type': 'application/json'},  
          success: function(res){  
            return typeof cb == "function" && cb(res.data)  
          },  
          fail: function(){  
            return typeof cb == "function" && cb(false)  
          }  
        })  
    }  


    module.exports = {  
      req: req  
    }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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

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

//app.js  
    var http = require('service/http.js')  
    App({  
      onLaunch: function () {  
        //调用API从本地缓存中获取数据  
        var logs = wx.getStorageSync('logs') || []  
        logs.unshift(Date.now())  
        wx.setStorageSync('logs', logs)  
      },  
      getUserInfo:function(cb){  
        var that = this  
        if(this.globalData.userInfo){  
          typeof cb == "function" && cb(this.globalData.userInfo)  
        }else{  
          //调用登录接口  
          wx.login({  
            success: function () {  
              wx.getUserInfo({  
                success: function (res) {  
                  that.globalData.userInfo = res.userInfo  
                  typeof cb == "function" && cb(that.globalData.userInfo)  
                }  
              })  
            }  
          })  
        }  
      },  
      globalData:{  
        userInfo:null  
      },  
      func:{  
        req:http.req  
      }  
    }) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

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

var app = getApp()  
    Page({  
      data: {  

      },  
      onLoad: function (opt) {  
        //console.log(opt.name)  
       app.func.req('/api/get_data',{},function(res){  
         console.log(res)  
        });  
      }  
    })  

posted on 2017-10-21 10:02  浙江百牛信息技术  阅读(471)  评论(0编辑  收藏  举报

导航