微信小程序入门篇(二)(wx.request的json数据传输)

时间:2024-02-26 07:56:24

wx.request使用

代码如下:

    wx.request({
      url: \'https://192.168.191.1:8443/vocation/bbb\',
      data: {name:"111",password:"123",id:"123"},
      method: \'post\', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
     // dataType:JSON,//该语句会将服务器端的数据自动转为string类型
      success: function(res){
        // success
        
        console.log("返回数据为:"+res.data.employees[1].firstName);
        console.log(\'submit success\');
      },
      fail: function() {
        // fail
        console.log(\'submit fail\');
      },
      complete: function() {
        // complete
        console.log(\'submit comlete\');
      }
    })

  服务器端的代码:

       JSONObject jsonObject = JSONObject.fromObject(getRequestPayload(request));
            String name=jsonObject.get("name").toString();
            String password=jsonObject.get("password").toString();
            String s = "";
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            System.out.println(name + " " + password);
            s = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
            response.getWriter().write(s);

数据传送到微信端是[object object]的形式,因此直接可以通过res.data.employees[1].firstName获得对象的数据