按照文檔,肯定是這么寫.那就入坑了.
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ù)的.需要轉格式.
下面直接貼代碼:
3.1
//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' );
登錄后復制
3.2
{{toastText}}
{{city_name}} {{date}} {{info}}
登錄后復制
3.3
//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,
}
登錄后復制
評論部分:
又試了幾個接口,部分可以提交數(shù)據(jù).應該是個bug.只能等官方正式版本了.
我剛才用其他的post請求也不行.但是這個確實拿到數(shù)據(jù)了.你試試看,接口地址:http://op.juhe.cn/onebox/weather/query?兩個參數(shù),cityname,key.cityname隨便寫城市名字,key是我申請的,key=1430ec127e097e1113259c5e1be1ba70 我明天再研究下.看看是為什么其他的不行.
更多小程序:post請求相關文章請關注愛掏網 - it200.com!
聲明:所有內容來自互聯(lián)網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯(lián)系我們進行處理。