Yalda

哈库呐玛塔塔

嗨,我是张志方,一名 iOS 开发者。


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

最近微信小程序开始开放测试了,小程序提供了很多api,极大的方便了开发者,其中网络请求api是wx.request(object),这是小程序与开发者的服务器实现数据交互的一个很重要的api。 大家可以先看官方文档微信小程序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)  
         }  
       })  
     }  

下面我们把请求写在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  
    }  

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

这时这个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)  
        });  
      }  
    })  
最近的文章

ARC内存管理

现阶段移动端iOS开发基本都是使用ARC模式进行开发,但是在有的情况下也是需要使用MRC的,比如在使用系统没有加入ARC管理内存的类的时候,比如使用CoreFoundation下的文件就需要我们...…

继续阅读

更早的文章

Git常用命令行总结

查看、添加、提交、删除、找回,重置修改文件 git help <command> 显示command的help git show 显示某次提交的内容 git show $id...…

继续阅读
-->