溫馨提示×

溫馨提示×

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

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

微信小程序與java后臺數(shù)據(jù)交互

發(fā)布時間:2020-05-31 11:34:03 來源:網(wǎng)絡(luò) 閱讀:3131 作者:101ttyy 欄目:開發(fā)技術(shù)

先到 官網(wǎng) 申請賬號和下載 微信開發(fā)工具。

進(jìn)入微信開發(fā)工具,index.wxml關(guān)鍵代碼入下:

  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
  <view>
    <button bindtap='change'>變更</button>
  </view>

index.js關(guān)鍵代碼如下:
get提交方式:

change: function () {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/myTest/wxxcx/wxlogin.do',
      method: 'get',
      data: { pass: 'text', name: '測試11' },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          motto: res.data[0].name
        });
      },
      fail: function (err) {
        console.log("sssssssssssss" + err.data);
      }
    })
  },

post提交方式:

change: function(){
    var that = this;
    wx.request({
      url: 'http://localhost:8080/myTest/wxxcx/wxlogin.do',
      method:'post',
      data:{pass:'text',name:'測試11'},
      header: {
        'content-type': 'application/x-www-form-urlencoded' //post提交方式這里json需改成這個x-www-form-urlencoded,否則后臺接收不到數(shù)據(jù),原因參考:http://blog.csdn.net/mhmyqn/article/details/25561535/
      },
      success: function(res){
        that.setData({
          motto: res.data[0].name
        });
      },
      fail:function(err){
       console.log("sssssssssssss"+err.data);
      }
    })
  }

java后臺關(guān)鍵代碼:

@RequestMapping(value = "wxlogin.do")
    public String wxlogin(String name,HttpSession session, HttpServletRequest req, HttpServletResponse resp, Model model) {
        resp.setContentType("text/json");
        resp.setCharacterEncoding("utf-8");
        String pass = (String) req.getParameter("pass");
        log.info("pass==" + pass + ",name=" + name);
        PrintWriter pw = null;
        Map map = new HashMap();
        map.put("pass", pass);
        map.put("status", "進(jìn)入后臺了");
        map.put("name", name);
        JSONArray json = JSONArray.fromObject(map);
        try {
            pw = resp.getWriter();
            pw.print(json);
        } catch (IOException e) {
            log.info(e);
            log.error(e);
            e.printStackTrace();
        } finally {
            if (pw != null)
                pw.close();
        }
        return null;
    }

定義了個內(nèi)容變更按鈕
調(diào)試界面如下:
微信小程序與java后臺數(shù)據(jù)交互
單擊變更內(nèi)容后,java后臺輸出:
微信小程序與java后臺數(shù)據(jù)交互
微信開發(fā)工具調(diào)試界面
微信小程序與java后臺數(shù)據(jù)交互
數(shù)據(jù)交互成功:
需要注意一點(diǎn),微信開發(fā)工具wx.request要調(diào)用本地localhost項(xiàng)目,需在微信項(xiàng)目開發(fā)工具項(xiàng)目設(shè)置里勾選不校驗(yàn)合法域名。。。選項(xiàng)

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

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

AI