您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

微信小程序 POST请求(网络请求)详解及实例代码

2024/3/25 8:48:43发布31次查看
微信小程序 post请求
微信小程序开发中网络请求必不可少.get.post请求是最常用的.get请求,post请求的时候有好几个坑.我已经为大家填好了.
<img src="http://img.blog.csdn.net/20161017170933243?watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity/center" align="middle" alt="" />
按照文档,肯定是这么写.那就入坑了.
1. 'content-type': 'application/json'用在get请求中没问题.
post请求就不好使了.需要改成: "content-type": "application/x-www-form-urlencoded"
2016.11.10更新:有同学在将content-type 修改为小写后,post请求成功.
2. 加上method: "post"
3.data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }写成json格式这样也是请求不到数据的.需要转格式.
下面直接贴代码:
3.1
<span style="font-size:24px;">//index.js //获取应用实例 var app = getapp() page( { data: { toasthidden: true, city_name: '', }, onload: function() { that = this; wx.request( { url: "http://op.juhe.cn/onebox/weather/query", header: { "content-type": "application/x-www-form-urlencoded" }, method: "post", //data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }, data: util.json2form( { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }), complete: function( res ) { that.setdata( { toasthidden: false, toasttext: res.data.reason, city_name: res.data.result.data.realtime.city_name, date: res.data.result.data.realtime.date, info: res.data.result.data.realtime.weather.info, }); if( res == null || res.data == null ) { console.error( '网络请求失败' ); return; } } }) }, ontoastchanged: function() { that.setdata( { toasthidden: true }); } }) var that; var util = require( '../../utils/util.js' );</span>
3.2
<span style="font-size:24px;"><!--index.wxml--> <view class="container"> <toast hidden="{{toasthidden}}" bindchange="ontoastchanged"> {{toasttext}} </toast> <view>{{city_name}}</view> <view>{{date}}</view> <view>{{info}}</view> </view></span>
3.3
<span style="font-size:24px;">//util.js function json2form(json) { var str = []; for(var p in json){ str.push(encodeuricomponent(p) + "=" + encodeuricomponent(json[p])); } return str.join("&"); } module.exports = { json2form:json2form, }</span>
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product