微信小程序开发之网络请求(POST请求)

来源:互联网 发布:逐点比较圆弧插补算法c 编辑:程序博客网 时间:2024/06/06 00:01

微信小程序开发中网络请求必不可少.GET.POST请求是最常用的.GET请求

POST请求的时候有好几个坑.我已经为大家填好了.

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <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

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:24px;">//index.js  
  2. //获取应用实例  
  3. var app = getApp()  
  4. Page( {  
  5.   data: {  
  6.     toastHidden: true,  
  7.     city_name: '',  
  8.   },  
  9.   onLoad: function() {  
  10.     that = this;  
  11.     wx.request( {  
  12.       url: "http://op.juhe.cn/onebox/weather/query",  
  13.       header: {  
  14.         "Content-Type""application/x-www-form-urlencoded"  
  15.       },  
  16.       method: "POST",  
  17.      //data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" },  
  18.       data: Util.json2Form( { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }),  
  19.       complete: function( res ) {  
  20.         that.setData( {  
  21.           toastHidden: false,  
  22.           toastText: res.data.reason,  
  23.           city_name: res.data.result.data.realtime.city_name,  
  24.           date: res.data.result.data.realtime.date,  
  25.           info: res.data.result.data.realtime.weather.info,  
  26.         });  
  27.         if( res == null || res.data == null ) {  
  28.           console.error( '网络请求失败' );  
  29.           return;  
  30.         }  
  31.       }  
  32.     })  
  33.   },  
  34.   onToastChanged: function() {  
  35.     that.setData( { toastHidden: true });  
  36.   }  
  37. })  
  38. var that;  
  39. var Util = require( '../../utils/util.js' );</span>  

3.2

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:24px;"><!--index.wxml-->  
  2. <view class="container">  
  3.    <toast hidden="{{toastHidden}}" bindchange="onToastChanged">  
  4.         {{toastText}}  
  5.     </toast>  
  6.     <view>{{city_name}}</view>  
  7.     <view>{{date}}</view>  
  8.     <view>{{info}}</view>  
  9. </view></span>  
3.3

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:24px;">//util.js  
  2. function json2Form(json) {  
  3.     var str = [];  
  4.     for(var p in json){  
  5.         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));  
  6.     }  
  7.     return str.join("&");  
  8. }  
  9. module.exports = {  
  10.   json2Form:json2Form,  
  11. }</span>  


1 0