微信小程序ajax请求接口

最近在入门微信小程序

其实web应用这块,就是请求数据,渲染数据

那么在微信小程序中如何请求外部接口呢

小程序目录结构

![](http://static.yuanchengzhushou.cn/program.png)

index.wxml

```


Weixin
{{userInfo.nickName}}
{{index}}:{{item.name}}

```

app.js

```
App({
onLaunch: function() {
//调用API从本地缓存中获取数据
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
get_a_test:function(){
console.log('this is a test')
},
getUserInfo: function(cb) {
var that = this
if (this.globalData.userInfo) {
typeof cb == "function" && cb(this.globalData.userInfo)
} else {
//调用登录接口
wx.getUserInfo({
withCredentials: false,
success: function(res) {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
},
globalData: {
userInfo: null,
college_change:false
}
})
```

index.js

```
// index.js
getApp().get_a_test();
var app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
Industry:{}
},
onLoad: function (res) {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function(userInfo){
//更新数据
that.setData({
userInfo:userInfo
})
})
wx.request({
url: 'https://interface.test.com/api/v2/manager/system/employee/index?page=1&per_page=10&working_status=&brand_ids=',//上线的话必须是https,没有appId的本地请求貌似不受影响
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
"authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6OTA5NVwvYXBpXC92MVwvYXV0aFwvYWRtaW5fbG9naW4iLCJpYXQiOjE2NzI5MTAzMTgsImV4cCI6MTY3Mjk5NjcxOCwibmJmIjoxNjcyOTEwMzE4LCJqdGkiOiJFUVNXRkdJSExpRWNRNTBZIiwic3ViIjoxNzAsInBydiI6IjU1MDk4MTJlNTk0YjlmMjlhNTg4ZGM5MTJjODdmNWJhMWI2NzM2YzQifQ.W9pJsLreCwJwj9TRUn356auhM7B4USxZb8p9egD9okU"
}, // 设置请求的 header
success: function(res){
//console.log(res.data.result)
console.log(res.data.data.data)
that.setData({
Industry:res.data.data.data
})
},
fail: function() {
// fail
console.log('fail');
},
complete: function() {
// complete
console.log('complete');
}
})
}
})
```

```
http://wjhsh.net/zmdComeOn-p-11918375.html
https://www.gxlcms.com/JavaScript-252287.html
https://www.gxlcms.com/JavaScript-252286.html
```

    A+
发布日期:2023年01月09日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: