index.wxml
<view class="container"> <text>{{txt}}</text> <input name="name" type="text" id='text' bindchange="xyz"/> <button id="btn" bindtap="abc" >提交</button> </view>
index.js
//index.js
//獲取應用實例
const app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
txt:"",
},
//事件處理函數
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
abc:function(e){//該函數用於和后台交互
// var v = e
var v = this.txt;
var self=this; //關鍵代碼,這要操作程序無法運行
wx.request({
url: 'https://域名/jous/hello.do', //僅為示例,並非真實的接口地址
data: {
name:v,
},
header: {
'content-type': 'application/json' // 默認值
},
success(res) {
//console.log(res.data)
this.txt=res.data//把交互的參數值賦值給全局變量
console.log("aaa" + this.txt)//控制台輸出變量
self.setData({//動態設置顯示的值
txt: this.txt
})
}
})
},
xyz: function (e) {//從輸入框獲取數據
var v = e.detail.value
this.txt=v;//將獲取到的值賦值給中間變量
},
})
JAVA代碼
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String msg = "Hello"+name;
JsonUtil.printJson(response,msg);
}
JAVA 轉Json代碼
public static void printJson(HttpServletResponse response, Object obj) throws IOException {
// 返回數據,返回數據類型是json
response.setContentType("application/json");
// 返回數據編碼UTF-8
response.setCharacterEncoding("UTF-8");
// 返回數據,通過gson將數據返回給Ajax 通過gson工具提高工作效率
response.getWriter().write(new Gson().toJson(obj));
}
