小程序开发之网络请求的封装教程

巴扎黑
巴扎黑 原创
2017-08-17 14:56:46 1091浏览
在这里首先声明一个小程序文档的bug,导致大伙们在请求的时候,服务器收到不到参数的问题
示例代码:
wx.request({
 url: 'test.php', //仅为示例,并非真实的接口地址
 data: {
 x: '' ,
 y: '' },
 header: { 'Content-Type': 'application/json' },
 success: function(res) {
 console.log(res.data) }})

其中header 中的Content-Type,应该用小写content-type才能让服务器收到参数。让我折腾的好久,改了服务器仍然不行,原来是这个问题。参数在request payload中,服务器不能收到,使用如下转换之后
function json2Form(json) { 
 var str = []; 
 for(var p in json){ 
 str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); 
 } 
 return str.join("&"); }

图片:1.png



最终还是认为是content-type的问题。最后改小写就ok,觉得微信这么牛逼的团队,犯了一个很低级 的错误,把我开发者折腾的爬了。不说,上代码吧。
1 、Http请求的类

2、测试用例
2.1 get请求
//GET方式let map = new Map();map.set( 'receiveId', '0010000022464' );let d = json_util.mapToJson( util.tokenAndKo( map ) );console.log( d );var url1 = api.getBaseUrl() + 'SearchTaskByReceiveId?data='+d;network_util._get( url1,d,function( res ) {console.log( res );that.setData({
 taskEntrys:res.data.taskEntrys});}, function( res ) {console.log( res );});

2.2 POST请求
//Post方式 let map = new Map();
 map.set( 'receiveId', '0010000022464' ); let d = json_util.mapToJson( util.tokenAndKo( map ) );
 console.log( d ); var url1 = api.getBaseUrl() + 'SearchTaskByReceiveId';
 network_util._post( url1,d, function( res ) {
 console.log( res );
 that.setData({
  taskEntrys:res.data.taskEntrys }); }, function( res ) {
 console.log( res ); });

图片:2.png



效果

图片:3.png

以上就是小程序开发之网络请求的封装教程的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。