一、封装Http
1.封装ajax
/* 默认赋值,回调函数,箭头函数 */
function http({url,callback,type="get"}){
$.ajax({
url,
type,
dataType:"json",
success: res=>{
callback(res)
}
})
}
2.调用ajax
var url = "http://localhost:8080/"
http(url,handleData); //调用封装的ajax函数
//handleData就是 载入成功时 的回调函数
function handleData(res){
for(var key in res){
var p = document.createElement("p");
p.innerHTML = res[key];
document.body.append(p)
}
}
二、Class封装Http
models/HTTP.js
//HTTP.js
var baseUrl="https://music.aityp.com/";
class HTTP{
static request({url,data}){
return new Promise((resolve,reject)=>{
wx.request({
url: baseUrl+url,
data,
header: {'content-type':'application/json'},
method: 'GET',
dataType: 'json',
responseType: 'text',
success: (res)=>{
resolve(res)
},
fail: (err)=>{
reject(err)
}
});
})
}
}
module.exports=HTTP;
models/IndexModel
const HTTP=require('./HTTP')
class IndexModel extends HTTP{
static getArtists(){
return this.request({
url:"top/artists"
})
}
}
module.exports=IndexModel
index.js—页面使用
const IndexModel=require('../../models/IndexModel') //1.导入
Page({
data: {
artists:[]
},
onLoad() {
IndexModel.getArtists().then(res=>{ //使用
var {artists}=res.data;
this.setData({
artists
})
});
},
})