php封装request函数,微信小程序对wx.request函数进行封装操作的代码示例

本文介绍了如何在微信小程序中使用`networkEngine`进行数据发送,通过`wx.request`实现AJAX请求,展示了参数传递和错误处理的方式。重点在于`send`函数的使用及其在页面初始化、数据加载和接口调用中的应用。
摘要由CSDN通过智能技术生成

//app.js

App({

onLaunch: function () {

},

networkEngine: require('utils/network.js')

})

// /utils/network.js

module.exports ={

send:function(){

console.log(arguments);

var that = this;

var pack = {};

if(arguments.length == 1){

pack = arguments[0];

}else if(arguments.length == 3){

pack.url = arguments[0];

pack.data = arguments[1];

pack.complete = arguments[2];

} else{

throw new Error('arguments_error');

}

var newPack = {};

newPack = pack.data;

var url = '';

if(pack.url.indexOf('/') === 0){

url = pack.url.substr(1, pack.url.length - 1);

}else{

url = pack.url;

}

wx.request({

url: "https://xxxxx" + '/' + url,

data: newPack,

header:{

'Content-Type': 'application/json'

},

method: 'POST',

success:function(res){

console.log('res:', res);

pack.complete(res.data.code, res.data.msg, res.data.data, pack.data);

},

fail:function(res){

pack.complete(-1, 'wechat_error', res, pack.data);

},

complete: function (res) {

}

})

}

}

//index.js

//获取应用实例

const app = getApp()

//import ListLodingState from '../list_loading_state/list_loading_state.js';

Page({

data: {

isVip: 50

},

onLoad: function () {

let instance = this;

instance.componentInit();

instance.initData();

},

componentInit:function(){

let instance = this;

// instance.listLoadingState = new ListLoadingState(instance);

},

initData: function(){

let self = this;

self.loadData();

},

loadData: function(){

let self = this;

let instance = this;

let cmd = "isVip.php";

let paramter = {

user_id: 61152144

}

let successFn = function(data, app, instance){

console.log("1st request");

}

let errorFn = function(){

}

self._ajax(app, instance, cmd, paramter, successFn, errorFn);

},

_ajax: function(app, instance, cmd, paramter, successFn, errorFn){

let appTemp = app;

let instanceTemp = instance;

app.networkEngine.send(cmd, paramter, function(code, msg, data){

if(code == 0){

successFn(data, appTemp, instanceTemp);

instance.setData({

pageLoading: true,

show_network_error: false,

});

} else {

errorFn('微信调用networkEngine出现错误');

instance.setData({

pageLoading: true,

show_network_error: true,

});

}

})

}

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值