记录小程序 常用方法封装

本文介绍了如何在微信小程序中封装POST和GET请求接口,分别处理form表单和JSON数据。通过wx.request进行网络请求,并在成功或失败时显示加载动画和错误提示。同时,提供了调用封装接口的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//封装接口post  from表单类型

function way1(url, data, cb) {

	wx.showLoading({}) //加载动画  

	wx.request({

		url: url, //域名 (据情况而定)  url为地址

		data: data, //所需要传的参数

		header: {

			"Content-Type": "application/x-www-form-urlencoded", // 处理form表单的请求头

			"cache-control": "no-cache" //处理在回调时反应慢的问题(可不写)

		},

		method: 'POST', //方式为post

		dataType: 'json',

		responseType: 'text',

		success: function(res) { // 请求成功后

			wx.hideLoading(); //请求成功后加载动画结束

			return typeof cb == "function" && cb(res) // 用来判断返回的是否是函数

		},

		fail: function(res) { //请求失败

			wx.hideLoading();

			wx.showModal({

				title: '网络错误',

				content: '网络出错,请刷新重试',

				showCancel: false

			})

			return typeof cb == "function" && cb(false)

		},

	})

}



//封装接口post    json类型

function way2(url, data, cb) {

	wx.showLoading({})

	wx.request({

		url: url,

		data: data,

		header: {

			"Content-Type": "application/json;charset=UTF-8",

			"cache-control": "no-cache"

		},

		method: 'POST',

		dataType: 'json',

		responseType: 'text',

		success: function(res) {

			wx.hideLoading();

			return typeof cb == "function" && cb(res)

		},

		fail: function(res) {

			wx.hideLoading();

			wx.showModal({

				title: '网络错误',

				content: '网络出错,请刷新重试',

				showCancel: false

			})

			return typeof cb == "function" && cb(false)

		},

	})

}



//封装接口get 基本都是json类型的

function way3(url, data, cb) {

	wx.showLoading({})

	wx.request({

		url: url,

		data: data,

		header: {

			"Content-Type": "application/json;charset=UTF-8",

			"cache-control": "no-cache"

		},

		method: 'GET',

		dataType: 'json',

		responseType: 'text',

		success: function(res) {

			wx.hideLoading();

			return typeof cb == "function" && cb(res)

		},

		fail: function(res) {

			wx.hideLoading();

			wx.showModal({

				title: '网络错误',

				content: '网络出错,请刷新重试',

				showCancel: false

			})

			return typeof cb == "function" && cb(false)

		},

	})

}
//将方法暴露
module.exports = {
	upload: way1,
	post: way2,
	get: way3,
}
api.get(app.globalData.getSkill_label,{},(res)=>{console.log(res)}) 使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值