欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

微信小程序(十八)——封装request请求(ajax)请求后台接口

微信小程序(十八)——封装request请求(ajax)请求后台接口

2018年08月23日 10:46:13 开猿节流 阅读数:302                
 版权声明:本文为博主原创文章,未经博主允许不得转载。交流联系QQ:634487911 https://blog.csdn.net/qq_38191191/article/details/81976265

官方的request请求:

wx.request(OBJECT)

wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。

OBJECT参数说明:

参数名类型必填说明
urlString开发者服务器接口地址
dataObject、String请求的参数
headerObject设置请求的 header , header 中不能设置 Referer
methodString默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
successFunction收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'}
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

  1. wx.request({
  2. url: 'test.php',
  3. data: {
  4. x: '' ,
  5. y: ''                            
  6. },
  7. header: {
  8. 'Content-Type': 'application/json'                            
  9. },
  10. success: function(res) {
  11. console.log(res.data)
  12. }
  13. })
               

但是调用很多接口的时候,会非常频繁的使用request,所以现在做一下简单的封装:放在公共函数util文件中

               

代码:

  1. /**                            
  2.   * 封装ajax请求方法,加入header,loading效果                            
  3.   * url 请求地址的uri                            
  4.   * data 请求数据                            
  5.   * method 请求数据类型,默认GET请求                            
  6.   * success 成功回调函数                            
  7.   * fail 失败回调函数                            
  8.   */                            
  9. ajax(url, data, method, success, fail, loading = true) {
  10. if(loading){
  11. wx.showLoading({
  12. title: '正在加载中...',
  13. });
  14. }
  15. let _this = this;
  16. wx.request({
  17. url: _this.base_url + url,
  18. data: data,
  19. method: method || 'GET',
  20. header: {
  21. 'Authorization': 'Bearer ' + (wx.getStorageSync('token') || '')
  22. },
  23. success: (res) => {
  24. if(res.statusCode == 200){
  25. if (typeof success == 'function') {
  26. success(res.data);
  27. }
  28. }else if (res.statusCode == 401){
  29. wx.showModal({
  30. title: '错误提示',
  31. content: '当前您还未登录,请先登录',
  32. success: res => {
  33. if (res.confirm) {
  34. wx.switchTab({
  35. url: '../user/index',
  36. })
  37. }
  38. }
  39. })
  40. } else {
  41. if (typeof fail == 'function') {
  42. fail();
  43. }
  44. }
  45. },
  46. fail: res => {
  47. },
  48. complete: () => {
  49. wx.hideLoading();
  50. }
  51. })
  52. },
               

在其他.js中引入

  1. var util = require('../../utils/util.js');
  2. util.ajax(url, userInfo, 'POST', res => {
  3. })
               

 


普通分类: