The last article mainly talked about the small program TAB switching, data binding and data storage, this article continues to introduce the network communication and data parsing of the small program

Focus on Spring Boot+ micro services, mini programs, Flutter, Android, regularly share articles and video tutorials, reply to Java materials after attention, receive the learning dry goods carefully prepared for you!

This article is the seventh in the series of small programs, and knowing the previous articles will help you understand it better:

1. Applets (I) Understand applets 2. Applets (II) APPID fetching and project directory structure 3. Small program (3) life cycle 4. Small program (4) development and debugging methods and real machine debugging 5. Applets (5) Applets create project parsing 6. Applets (6) TAB switching and data binding, data storage

preface

One, request interface description two, request interface way three, interface call four, interface paging call five, interface data parsing

1. Request interface description

The official interface function of the small program is called wx.request. The request method is relatively simple. The following is an example of the request provided on the official website.





wx.request({
Url: 'test.php', // this is just an example, not a real interface address
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})


· URL: address of the requested interface

· Data: request parameters

· Header: Request header, including host, user-agent, Accept, ACCpt-language, Referer, etc

· Method: Request mode: POST/GET

· Success: When the interface request is successful, the applet will automatically trigger this function and get the data (JSON) returned from the server. The data retrieved after a successful request is the result parameter of the SUCCESS function.

· Fail: When the interface call fails, the applet will trigger this function, returning an error message

· Complete: Callback function at the end of the interface call (both successful and unsuccessful), passing data to the WXML page via that.setData.

2. Request interface mode

Interface requests are mostly called as utility classes, with file names util and function names getReq and req providing methods to expose interfaces through module.exports

module.exports = {
req: req,
getReq: getReq,
};


Get request mode // GET request mode

function getReq(url, data, cb) {
try {
const token = wx.getStorageSync('bus_token');
if (token) {
// Do something with return value
console.debug('token111=' + token);
}

// data.appid = AppConf.appid;
// data.appsecret = AppConf.appsecret;
wx.request({
url: rootDocment + url,
data: data,
method: 'get',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': token,
},
success: function (res) {
return typeof cb === 'function' && cb(res.data);
},
fail: function () {
return typeof cb === 'function' && cb(false);
},
});
} catch (e) {
// Do something when catch error
}
}


Post request mode // POST request mode

function req(url, data, cb) {
try {
const token = wx.getStorageSync('bus_token');
if (token) {
// Do something with return value
console.debug('token111=' + token);
}

data.appid = AppConf.appid;
data.appsecret = AppConf.appsecret;
wx.request({
url: rootDocment + url,
data: data,
method: 'post',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
"authorization": token
},
success: function (res) {
return typeof cb === 'function' && cb(res.data);
},
fail: function (error) {
console.debug(error);
return typeof cb === 'function' && cb(false);
},
});
} catch (e) {
// Do something when catch error
}
}


3.Interface call

(1) GET request invocation


(2) POST request invocation

4.Interface paging call

(a) set paging parameters






(two) set the refresh configuration, after setting, it will automatically call the drop-down effect

(3) Description of refresh function

1. The top and bottom refresh effects are initialized. The default drop-down refresh effect disappears and more effects are hidden

2. Load state is added by showLoading

3. Invoke the interface function

4. The interface status changes after the refresh

(4) load more function description


1. Top and bottom refresh effects initialized

2. Determine whether there are more conditions to be loaded

Page number ++ and call the interface function

4. The interface status changes after the refresh

5.Interface data parsing

Applets have two types of data: objects and arrays.


1. Object parsing can directly obtain information from objects. For example:

{"code": "123"."message": "Request successful"}Copy the code

wx.request({url: 'http://www.intmote.com/myproject/test/new_file.json',header: {'content-type': 'application/json'},success: function(res) {console.log(res.code)that.setData({goldData: res.code,// Get code information from the object})}})Copy the code

2. Array parsing

{"code": "123"."message": [{"code2": "123"."message2": "Request successful"}, {"code2": "123"."message2": "Request successful"}}]Copy the code


Gets information about the Message array and the first data object in the array

wx.request({url: 'http://www.intmote.com/myproject/test/new_file.json',header: {'content-type': 'application/json'},success: function(res) {console.log(res.code)that. SetData ({goldData: res.message,// Obtain the array set information goldData2: Res.message [0].code2,// Get code2 data from first object in array})}})Copy the code


6.Var let const difference

A variable declared in let mode is a local variable, which is valid only in the range closest to {}. After {}, the variable can no longer be used, otherwise an undefined error will be reported for the variable. That is, the variable is scoped within the code block in which it resides. //index.js// Get the application instance

const app = getApp()Page({  data: {  },   onLoad: function () {    console.log('App onLoad'); / / useletThe way I is declared is only inforValid within the cycle, inforAn out-of-loop reference will report an undefined error Ifor (let i = 0; i < 20; i++) {      console.log('The value of I in the for loop is'+i); } console.log(I); },})Copy the code

(2) of the var

Variables declared by var are global variables whose scope is within the function. So the important point is that the rest of the functions in the current JS file, if directly used, will also report undefined error. See the incorrect use of var below for details.

Page({  data: {    name: 'Newly insured',// default value of name}, addPerson:function (event) {    // this.data.name = 'save'    this.setData({      name: 'save'})},onLoad() {    console.log('App onLoad'); // Var I is valid in the onLoad function, but not in other functions.for (var i = 0; i < 10; i++) {      console.log('The value of I in the for loop is'+ i); // output 0-9} console.log('Value of I in onLoad'+ i); // output 10},})Copy the code


Incorrect use of var

In the addPerson: function of the index.js file, printing the var variable I declared in the onLoad function will report an undefined error for variable I.

Page({  data: {    name: 'Newly insured',// default value of name}, addPerson:function (event) {    // this.data.name = 'save'    this.setData({      name: 'save'    })    console.log('The value of I in the addPerson function'+i); },onLoad() {    console.log('App onLoad');    for (var i = 0; i < 10; i++) {      console.log('The value of I in the for loop is' + i);    }    console.log('Value of I in onLoad'+ i); }})Copy the code

Const PI=3.14; const PI=3.14;

conclusion

Using applets makes it very easy and fast to develop small applications, we don’t have to worry about the components in the API and so on, the applicable version and so on, we want to use anything, just according to the components and API can be added.

Demo address: github.com/chenjianpen… Code display small program looks more clear, you can move small program view.

Procedural workplace, a dedicated workplace programmer.