出于安全考虑,小程序对数据接口的请求有要求:
-
只能请求https类型的接口
-
必须将接口的域名添加到信任列表中
配置合法域名
登录小程序公众平台--->开发管理---->开发设置--->服务器域名--->修改合法域名
发起GET请求
wx.request({
url: 'example.php', //仅为示例,并非真实的接口地址
method:'GET',
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
在页面刚加载时请求数据
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
this.getData()
},
getData(){
wx.request({
url: 'https://www.escook.cn/slides', //仅为示例,并非真实的接口地址
method:'GET',
header: {
'content-type': 'application/json' // 默认值
},
success:(res)=>{
// console.log(res.data)
this.setData({
banners:res.data
})
}
})
},
发起Post请求
wx.request({
url: 'example.php', //仅为示例,并非真实的接口地址
method:'POST',
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
跳过request合法域名校验
后端程序员仅仅提供了http协议的接口,需要不校验合法域名
微信开发者工具---->详情---->不校验合法域名
没有跨域
跨域只存在于浏览器的web开发中,小程序是运行在微信环境中,小程序不存在跨域问题
Ajax技术的核心是依赖于浏览器的 XMLHttpRequest 对象,小程序是运行在微信环境中没有这个对象,小程序不能叫做ajax请求 叫做发起网络数据请求