具體的封裝可以參考寫的文章小程序獲取定位
文件夾位置如下:
image
因為平時ajax請求的url一般都是固定的,所以可以新建一個頁面用const定義常量統(tǒng)一放在一個頁面中。
下面是封裝函數(shù),按照之前上面文章的思路:
//將常用的變量用const存儲起來
export const TENCENTMAPURL = 'https://apis.map.qq.com/ws/geocoder/v1/'
export const TENCENTMAPKEY = 你的地圖key
// 將地址常量保存命名后期拼接使用
export const LOCALHOST = 'http://localhost:8888/'
//引入外部常量
import {
TENCENTMAPURL,
TENCENTMAPKEY,
LOCALHOST
} from '../utils/const.js'//注意相對路徑,不要引用錯了
//使用promise時,需要return,因為后面的then 需要調(diào)用return的值
export function $get(url, data) {
return request("GET", url, data)
}
export function $post(url, data) {
return request("POST", url, data)
}
function request(method, url, data) {
return new Promise((resolve, rejected) => {
//未獲取成功之前顯示加載中
wx.showLoading({
title: '加載中...',
})
wx.request({
method,
//url是拼接的,因為一般地址的前半部分是一樣的,如果請求的是其他網(wǎng)頁的話,用starsWith判斷開頭來決定是否要拼接,如下是一個三元表達(dá)式的判斷
url: url.startsWith('https://') ? url : LOCALHOST + url,
data,
success: (res) => {
resolve(res.data)
},
fail: (res) => {
rejected(res)
},
//當(dāng)獲取完成結(jié)束loading狀態(tài)
complete:(res)=>{
wx.hideLoading()
}
})
})
}
調(diào)用
$get('list').then(res=>{
console.log(res)
})