一、封装Http

1.封装ajax

  1. /* 默认赋值,回调函数,箭头函数 */
  2. function http({url,callback,type="get"}){
  3. $.ajax({
  4. url,
  5. type,
  6. dataType:"json",
  7. success: res=>{
  8. callback(res)
  9. }
  10. })
  11. }

2.调用ajax

  1. var url = "http://localhost:8080/"
  2. http(url,handleData); //调用封装的ajax函数
  3. //handleData就是 载入成功时 的回调函数
  4. function handleData(res){
  5. for(var key in res){
  6. var p = document.createElement("p");
  7. p.innerHTML = res[key];
  8. document.body.append(p)
  9. }
  10. }

二、Class封装Http

models/HTTP.js

  1. //HTTP.js
  2. var baseUrl="https://music.aityp.com/";
  3. class HTTP{
  4. static request({url,data}){
  5. return new Promise((resolve,reject)=>{
  6. wx.request({
  7. url: baseUrl+url,
  8. data,
  9. header: {'content-type':'application/json'},
  10. method: 'GET',
  11. dataType: 'json',
  12. responseType: 'text',
  13. success: (res)=>{
  14. resolve(res)
  15. },
  16. fail: (err)=>{
  17. reject(err)
  18. }
  19. });
  20. })
  21. }
  22. }
  23. module.exports=HTTP;

models/IndexModel

  1. const HTTP=require('./HTTP')
  2. class IndexModel extends HTTP{
  3. static getArtists(){
  4. return this.request({
  5. url:"top/artists"
  6. })
  7. }
  8. }
  9. module.exports=IndexModel

index.js—页面使用

  1. const IndexModel=require('../../models/IndexModel') //1.导入
  2. Page({
  3. data: {
  4. artists:[]
  5. },
  6. onLoad() {
  7. IndexModel.getArtists().then(res=>{ //使用
  8. var {artists}=res.data;
  9. this.setData({
  10. artists
  11. })
  12. });
  13. },
  14. })