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

it2022-05-05  173

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

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

 

最简单的用法如下(以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,必须要使用小写,使用大写不能正常发起请求!!


最新回复(0)