小程序ajax请求封装

小程序


1、建basehost.js,配置请求的基础域名

export default {
    doubanBaseHost: "https://douban.uieee.com",
    localBaseHost: "localhost:8080/"
}

2、新建 ajax.js,封装wx.request

import basehost from './basehost.js';
class Base{
	constructor(){}
	//wx.request 封装方法 promise
	request({url, params, method, hideLoading}){
		return new Promise((resolve,reject)=>{
			if(!hideLoading){
				wx.showLoading({
					mask:true,
					title:'加载中...',
				})
			}
			wx.request({
				url: basehost.doubanBaseHost + url,
				data: params,
				method,//post get put delete option
				header:{
					'content-type':'json',
				},
				//成功
				success(res){
					resolve(res.data);
					//if(res.code == 401){}
				},
				//失败
				fail(err){
					reject(err);
				},
				//完成
				complete(){
					wx.hideLoading();
				}
			});
		})
	}
}

export default Base;

3、新建api.js,封装api

import ajax from './ajax.js';
class Api extends ajax{
	constructor(){
		super();
	}
	//热门预告
	filmTeaters(params){
		return this.request({
			method:'GET',
			url:'/v2/movie/in_theaters',
			params,
			//hideLoading: true
		})
	}
}
export default new Api();

4、页面中使用

import Api from './../../utils/api.js'

Page({
	data:{
		theaters:{//热门电影
			list: [],
			total: 0
		}
	},
	onLoad(options){
		Api.filmTeaters({}).then(res=>{
			this.setData({
				theaters:{
					list: res.subjects,
					total: res.total,
				}
			});
			console.log(res);
		})
	}
})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值