web前端|js教程
微信小程序,request,网络请求
web前端-js教程小程序提供了很多api,极大的方便了开发者,其中网络请求api是wx.request(object)
,这是小程序与开发者的服务器实现数据交互的一个很重要的api。
采集 源码,vscode怎么写博客,ubuntu 16 rtx,tomcat页面报404,electron 爬虫,php创建服务器,seo排名费用报价,qq靓号网站源码模板,google 搜索页面模板lzw
官方参数说明如下
成绩查询网站源码,vscode暂停快捷键,ubuntu有线共享,tomcat归档下载地址,爬虫常用headers,php copy 中文,光泽正规seo联系方式,php 200源码网里面的网站下载,网址模板源码图改了lzw
OBJECT参数说明:
校园o2o系统源码3.4,vscode不显示文件夹,删除目录Ubuntu,tomcat战斗机推荐,爬虫技术师,php配置ssl证书,seo优化权重有什么用lzw
最简单的用法如下(以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.jsvar 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) }); }})
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在js中如何判断节假日
在Angular中如何实现查询天气预报
在Angular中如何实现显示输入内容
如果觉得《在微信小程序中如何使用request网络进行请求操作》对你有帮助,请点赞、收藏,并留下你的观点哦!