频道栏目
首页 > 资讯 > 微信公众平台开发 > 正文

微信小程序之POST请求

17-03-17        来源:[db:作者]  
收藏   我要投稿

微信小程序之POST请求。在微信小程序里post请求和get情求,写法差不多,但是还是有一点点不同的,下面利用post请求做一个查询天气的微信小程序demo。

页面代码:

 {{title}} 
 
    {{city_name}}  
    {{date}}  
    {{info}}  
 

js代码:

var app = getApp();
var that;  
var Util = require( '../../utils/util.js' );
Page( {  
  data: {    
    city_name: '', 
    title:'',
    red:'green'
  },  
  onLoad: function(options) {  
      this.setData({
          title:options.title
      })
    that = this; 
    wx.request( {  
      url: "http://op.juhe.cn/onebox/weather/query",  
      header: {  
      //请求头和ajax写法一样
        "Content-Type": "application/x-www-form-urlencoded"  
      },  
      method: "POST",   
      data: Util.json2Form( { cityname: "北京", key: "1430ec127e097e1113259c5e1be1ba70" }),  
      complete: function( res ) { 

         wx.showToast({
            title:'成功',
            icon:'success',
            duration:2000
         })

        that.setData( {   
            red:'red',
          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;  
        }  

         setTimeout(function(){
             wx.hideToast()
         },2000)
      }  
    })  
  }

})  

依赖util.js代码:

function json2Form(json) {  
    var str = [];  
    for(var p in json){  
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));  
    }  
    return str.join("&");  
} 

module.exports = {
  formatTime: formatTime,
  json2Form:json2Form,
}

展示图:
这里写图片描述

相关TAG标签
上一篇:向云服务器上传下载文件方法汇总
下一篇:Ubuntu下eclipse中安装Scala插件
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站