微信小程序request
2018-09-27 本文已影响0人
写给猫
request简介
wx.request用于发起HTTPS网络请求,其常用的参数有url(接口地址)、data(请求的参数)、header(设置请求的header)、method(http请求方法)、success(接口调用成功的回调函数)、fail(接口调用失败的回调函数)、complete(接口调用结束的回调函数,调用成功或失败都会执行)。
request事例
wx.request({
url: 'https://........' ,
data: {
pageindex: that.data.pageindex//当前页
},
header: {
"content-type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (res) {
console.log("success:" + res);
try {
if (res.data) {
//定义一个临时数据字典存储访问的网页数据
var tempResult = res.data.NEWS[1];
console.log("ssss" + tempResult);
var tempArrayInfo;
if (that.data.pageindex == 1) { //如果是重新从第一页开始请求,则清空之前保存的数据
tempArrayInfo = [];
} else {
tempArrayInfo = that.data.ArrNews; //没有更改筛选条件,即不是从第一页开始请求,则将之前已经获取到的数据赋值给tempArrayInfo,以便解析后将新的数据加到tempArrayInfo中(后)。
}
if (tempResult.length < 10) {
that.setData({
isLastPage: true
});
}
for (var i = 0; i < tempResult.length; i++) {
var infoDict = tempResult[i]; //每一条纪录
var Title = infoDict.title;
var SourceName = infoDict.source;
var DataTime = infoDict.time;
var Content = infoDict.article.content;
var tempDict = {};
tempDict["Title"] = Title; //定义左边键名,右边对应的键值
tempDict["SourceName"] = SourceName;
tempDict["DataTime"] = DataTime;
tempDict["Content"] = Content;
tempArrayInfo.push(tempDict);
}
that.setData({
ArrNews: tempArrayInfo, //将临时数组赋给这个arrNews空数组,则可以进行“item.键名”的使用
pageindex: that.data.pageindex + 1, //加载完一页数据下拉自动加载下一页数据
})
var arrContent = that.data.ArrNews;
wx.setStorageSync('content', arrContent); //设置缓存
} else { }
}
catch (e) {
}
wx.hideLoading();
},
fail: function (err) {
console.log("error:" + err);
wx.hideLoading();
}
});
}
代码解释:
url: 'https://........' ,
data: {
pageindex: that.data.pageindex//当前页
}
第一步是获取数据
使用url获取接口中返回的数据,同时将小程序js文件中定义的pageindex作为参数添加在url中。获取的数据,在success:function(res)
中
第二步是解析数据
这里需要两个数据字典tempResult
、 tempDict
和两个数组ArrNews
(定义在data中的全局变量)和 tempArrayInfo
。
其中tempResult
的作用是将success:function(res)
中的数据暂时存储起来,并进行解析,代码如下:var tempResult = res.data.NEWS[1];
。
tempArrayInfo
的作用是存储已经加载进去的数据,相当于一个中间存储变量,同时页面下拉刷新时,将之前加载的数据,继续加载到页面中。代码如下:
var tempArrayInfo;
if (that.data.pageindex == 1) { //如果是重新从第一页开始请求,则清空之前保存的数据
tempArrayInfo = [];
} else {
tempArrayInfo = that.data.ArrNews; //没有更改筛选条件,即不是从第一页开始请求,则将之前已经获取到的数据赋值给tempArrayInfo,以便解析后将新的数据加到tempArrayInfo中(后)。
}
tempDict
的作用是将tempResult
中解析出的每一个对象的属性,进行键名和键值的设置,设置之后,我们可以通过item.键名,来获取键值,然后将这些处理好的数据,放入tempArrayInfo
中。代码如下:
var tempDict = {};
tempDict["Title"] = Title; //定义左边键名,右边对应的键值
tempDict["SourceName"] = SourceName;
tempDict["DataTime"] = DataTime;
tempDict["Content"] = Content;
tempArrayInfo.push(tempDict);
ArrNews
是一个全局变量,是最早存储我们解析好的数据的数组,代码如下:
that.setData({
ArrNews: tempArrayInfo, //将临时数组赋给这个arrNews空数组,则可以进行“item.键名”的使用
pageindex: that.data.pageindex + 1, //加载完一页数据下拉自动加载下一页数据
})
通过以上两个步骤,就实现了将接口中的数据,读取、解析出来。