溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

小程序中post請求的示例

發(fā)布時(shí)間:2021-03-03 16:26:17 來源:億速云 閱讀:283 作者:小新 欄目:移動(dòng)開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)小程序中post請求的示例,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

小程序中post請求的示例

按照文檔,肯定是這么寫.那就入坑了.

1. 'Content-Type': 'application/json'用在get請求中沒問題.

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


2. 加上method: "POST"

3.data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }寫成json格式這樣也是請求不到數(shù)據(jù)的.需要轉(zhuǎn)格式.

下面直接貼代碼:

3.1

<span style="font-size:24px;">//index.js  
//獲取應(yīng)用實(shí)例  
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( '網(wǎng)絡(luò)請求失敗' );  
          return;  
        }  
      }  
    })  
  },  
  onToastChanged: function() {  
    that.setData( { toastHidden: true });  
  }  
})  
var that;  
var Util = require( '../../utils/util.js' );</span>

3.2

<span style="font-size:24px;"><!--index.wxml-->  
<view class="container">  
   <toast hidden="{{toastHidden}}" bindchange="onToastChanged">  
        {{toastText}}  
    </toast>  
    <view>{{city_name}}</view>  
    <view>{{date}}</view>  
    <view>{{info}}</view>  
</view></span>

3.3

<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>

小程序中post請求的示例

關(guān)于“小程序中post請求的示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI