小程序开发之网络请求
2017-02-23 15:55
169 查看
<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>
微信小程序开发中的网络请求离不开.get和.post请求。
如果直接按照文档来操作的话,肯定会碰到一些问题,下来就来列出这几个问题:
1、对于 header['content-type'] 为 'application/json'
的数据,用在get请求似乎 是没什么问题的,但是用在post请求的话就会出现问题,这是要将其改为header['content-type'] 为 'application/x-www-form-urlencoded'
2、如果是post请求一定要加上加上method:
"POST"
3、data:
{ cityname: "北京", key: "123456" }写成json格式这样也是请求不到数据的.需要转格式.
代码如下:
一、
//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' );
二、
<view class="container">
<toast hidden="{{toastHidden}}" bindchange="onToastChanged">
{{toastText}}
</toast>
<view>{{city_name}}</view>
<view>{{date}}</view>
<view>{{info}}</view>
</view>
三、
function json2Form(json) {
var str = [];
for(var p in json){
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
}
return str.join("&");
}
module.exports = {
json2Form:json2Form,
}
相关文章推荐
- 微信小程序基本的开发框架抽取,包括网络请求的二次封装,页面状态管理,常见页面模板封装
- 微信小程序开发之网络请求(GET请求)
- Win(Phone)10开发第(3)弹,简单的Demo程序网络请求json解析列表显示
- kotlin 开发 android 程序中网络http请求和线程的使用
- 微信小程序开发-网络请求
- 微信小程序开发之网络请求(GET请求)
- 解决·微信小程序开发-网络请求报Invalid request 400错误
- 微信小程序开发(二)--网络请求
- 微信小程序开发之网络请求(POST请求)
- 微信小程序开发之网络请求(POST请求)
- 微信小程序开发之网络请求(POST请求)
- 解决·微信小程序开发-网络请求报Invalid request 400错误
- 微信小程序开发之网络请求(POST请求)
- C#.Net 网络程序开发基础之TCP篇
- Visual C#.Net网络程序开发-Tcp篇
- 网络蜘蛛程序开发
- 网络程序开发-Socket篇
- C#.Net网络程序开发-Socket篇
- Visual C#.Net 网络程序开发-Socket篇
- 网络蜘蛛程序开发