欢迎光临,了解微信小程序开发,就上易用通!

post请求

发布:2018-01-25 11:42浏览: 来源:网络 作者:tianshu

post请求(图1) 


按照文档,肯定是这么写.那就入坑了.


1. 'Content-Type': 'application/json'用在get请求中没问题.

POST请求就不好使了.需要改成: "Content-Type": "application/x-www-form-urlencoded"



2. 加上method: "POST"

3.data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }写成json格式这样也是请求不到数据的.需要转格式.

下面直接贴代码:

3.1

 

  1. var app = getApp()  
  2. Page( {  
  3.   data: {  
  4.     toastHidden: true,  
  5.     city_name: '',  
  6.   },  
  7.   onLoad: function() {  
  8.     that = this;  
  9.     wx.request( {  
  10.       url: "https://op.juhe.cn/onebox/weather/query",  
  11.       header: {  
  12.         "Content-Type": "application/x-www-form-urlencoded"  
  13.       },  
  14.       method: "POST",  
  15.      //data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" },  
  16.       data: Util.json2Form( { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }),  
  17.       complete: function( res ) {  
  18.         that.setData( {  
  19.           toastHidden: false,  
  20.           toastText: res.data.reason,  
  21.           city_name: res.data.result.data.realtime.city_name,  
  22.           date: res.data.result.data.realtime.date,  
  23.           info: res.data.result.data.realtime.weather.info,  
  24.         });  
  25.         if( res == null || res.data == null ) {  
  26.           console.error( '网络请求失败' );  
  27.           return;  
  28.         }  
  29.       }  
  30.     })  
  31.   },  
  32.   onToastChanged: function() {  
  33.     that.setData( { toastHidden: true });  
  34.   }  
  35. })  
  36. var that;  
  37. var Util = require( '../../utils/util.js' );


3.2

 

  1. <view class="container">  
  2.    <toast hidden="{{toastHidden}}" bindchange="onToastChanged">  
  3.         {{toastText}}  
  4.     </toast>  
  5.     <view>{{city_name}}</view>  
  6.     <view>{{date}}</view>  
  7.     <view>{{info}}</view>  
  8. </view>

3.3
  1. function json2Form(json) {  
  2.     var str = [];  
  3.     for(var p in json){  
  4.         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));  
  5.     }  
  6.     return str.join("&");  
  7. }  
  8. module.exports = {  
  9.   json2Form:json2Form,  
  10. }



post请求(图2)





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。