您的位置:首页 > 理论基础 > 计算机网络

小程序开发之网络请求

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,
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  小程序