微信小程序的网络请求 —— 微信小程序教程系列(14)

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

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


19956127-29d5230fa0187a66.png

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

<view bindtap="bindSearchChange"><view>
bindSearchChange:function(){  
   wx.request({ 
     method:"GET",    //注意请求方式必须要大写!!!
     url:'xxxxxxxxx',  
     data:{},  
     header: {'content-type': 'application/json'},  //content-type必须要小写!!!
     success: function(res) {  
       console.log(res)  
     }  
   })  
 }  

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

var root = 'hxxxxx';//你的域名  
function req(url,data,cb){  
    wx.request({  
      url: root + 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 () {  
   //dosomething  
  },   
  func:{  
    req:http.req  
  }  
})  

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

var app = getApp()  
Page({  
  data: {  
      
  },  
  onLoad: function (opt) {  
    app.func.req('/api/get_data',{},function(res){  
       console.log(res)  
    });  
  }  
})  

目前,小程序还有待完善

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

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

2> content-type,必须要使用小写,使用大写不能正常发起请求!!
原文作者:michael_ouyang
原文链接:https://blog.csdn.net/michael_ouyang/article/details/55050486

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值