一,、寫在前面最近接觸了小程序的開發(fā),后端選擇Java,,因?yàn)樾〕绦虻拇a運(yùn)行在騰訊的服務(wù)器上,,而我們自己編寫的Java代碼運(yùn)行在我們自己部署的服務(wù)器上,所以一開始不是很明白小程序如何與后臺(tái)進(jìn)行通信的,,然后查找資料發(fā)現(xiàn)結(jié)合了官方提供的api后好像和我們普通的web前后端通信也沒有多大的區(qū)別,,有想法后就寫了這個(gè)測(cè)試程序。 二,、API文檔wx.request(OBJECT)發(fā)起網(wǎng)絡(luò)請(qǐng)求,。使用前請(qǐng)先閱讀說(shuō)明。 OBJECT參數(shù)說(shuō)明:
success返回參數(shù)說(shuō)明:
data 數(shù)據(jù)說(shuō)明: 最終發(fā)送給服務(wù)器的數(shù)據(jù)是 String 類型,,如果傳入的 data 不是 String 類型,,會(huì)被轉(zhuǎn)換成 String 。轉(zhuǎn)換規(guī)則如下:
示例代碼 wx.request({ url: 'test.php', //僅為示例,并非真實(shí)的接口地址 data: { x: '' , y: '' }, header: { 'content-type': 'application/json' // 默認(rèn)值 }, success: function(res) { console.log(res.data) } }) 三,、基本思路將數(shù)據(jù)通過(guò)get方式傳到Java servlet類,,servlet得到微信小程序的數(shù)據(jù)打印出來(lái)并返回一個(gè)數(shù)據(jù)給微信小程序,,從而實(shí)現(xiàn)一個(gè)最簡(jiǎn)單的前后端通信。 四,、關(guān)鍵代碼微信小程序代碼 index.wxml <view> <button bindtap='bindtest'>test</button> </view> index.js bindtest: function(){ wx.request({ url: 'http://localhost:8080/Demo01/servlet02', data:{ username:'001', password:'abc' }, method:'GET', header: { 'content-type': 'application/json' // 默認(rèn)值 }, success:function(res){ console.log(res.data); }, fail:function(res){ console.log(".....fail....."); } }) }, Java serlvet類代碼 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); /* 設(shè)置響應(yīng)頭允許ajax跨域訪問(wèn) */ response.setHeader("Access-Control-Allow-Origin", "*"); /* 星號(hào)表示所有的異域請(qǐng)求都可以接受,, */ response.setHeader("Access-Control-Allow-Methods", "GET,POST"); //獲取微信小程序get的參數(shù)值并打印 String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("username="+username+" ,password="+password); //返回值給微信小程序 Writer out = response.getWriter(); out.write("進(jìn)入后臺(tái)了"); out.flush(); } 五、效果演示前端控制臺(tái) ecplise控制臺(tái) 至此說(shuō)明微信小程序與Java后臺(tái)通信成功,!當(dāng)然這是最簡(jiǎn)單的通信,,比較復(fù)雜的是需要對(duì)Json數(shù)據(jù)的處理,以后有時(shí)間再總結(jié)下,。 |
|