微信小程序 SDK 剛剛出來,就已經有一堆入門教程了。然而並沒有關(guan) 於(yu) 如何在微信小程序中進行網絡通訊的教程,所以我們(men) 今天就來講一下新鮮出爐的獨門絕技——hprose 如何在微信小程序中實現通訊。
首先下載微信小程序開發工具,之後安裝。
然後按照網上那一堆微信小程序 Hello World 教程創建一個(ge) 小程序。
接下來我們(men) 下載 hprose-html5 或者 hprose-js。推薦使用 hprose-html5 版本,這個(ge) 版本更小,支持二進製數據傳(chuan) 輸,而且更快。
可以用 git clone 下載,也可以隻下載 dist 目錄下的文件,以 hprose-html5 版本為(wei) 例:
hprose-html5.src.js 是源碼版本 hprose-html5.js 是壓縮版本
這兩(liang) 個(ge) 版本都可以用。調試階段建議用源碼版本。但不要使用 hprose-html5.min.js 版本,這個(ge) 版本是壓縮版本的,不支持在微信小程序中編譯。
之後,你可以把它們(men) 複製到你創建的那個(ge) 微信小程序的 utils 目錄下(複製其中一個(ge) 就可以),然後將它改名為(wei) hprose.js(這一步可選,隻為(wei) 後麵引用的時候,名稱統一)。
接下來,打開 pages/index/index.js 文件。
在開頭加上:
var hprose = require('../../utils/hprose.js');
然後在 onLoad 事件中加入以下代碼:
var client = hprose.Client.create("https://www.hprose.com/example/", ["hello"]);
client.hello("world", function(result) {
console.log(result);
});
總體(ti) 看上去是這樣的:
//index.js
var hprose = require('../../utils/hprose.js');
//獲取應用實例var app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {}
},
//事件處理函數
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
console.log('onLoad')
var client = hprose.Client.create("https://www.hprose.com/example/", ["hello"]);
client.hello("world", function(result) {
console.log(result);
});
var that = this
//調用應用實例的方法獲取全局數據
app.getUserInfo(function(userInfo){
//更新數據
that.setData({
userInfo:userInfo
})
})
}
})
然後點編譯,運行,如果你的網絡沒有問題的,你會(hui) 在調試控製台中看到:
這裏寫(xie) 圖片描述
好了,就這麽(me) 簡單,接下來,你就可以用 hprose 來做微信小程序開發了。