微信小程序之網絡通信


關於網絡通信,這里我使用的是wx.request,官方代碼示例如下:

wx.request({
  url: 'test.php', //僅為示例,並非真實的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默認值
  },
  success (res) {
    console.log(res.data)
  }
})

對於初學者而言,官方示例可能會看不怎么懂,所以我就以我自己當初項目驅動學習的方式(開發個人的記賬小程序)來作為學習實例。

以登錄來說,效果圖如下:

此次示例包含表單校驗和網絡請求,代碼如下:
login.js

// pages/login/login.js
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    username: "",
    password: ""

  },
   register:function(e){
    wx.navigateTo({
      url: '../register/register'
    })

  },
  formSubmit: function(e) {
    console.log(e.detail.value.email);
    console.log(e.detail.value.pwd)
    var username = e.detail.value.email;
    var password = e.detail.value.pwd;
    var emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if (username == null || username == "") {
      wx.showToast({
        title: "用戶名不能為空",
        icon: 'none',
        duration: 1500
      })
    } else if (!emailReg.test(username)) {

      wx.showToast({
        title: "郵箱有誤",
        icon: 'none',
        duration: 1500
      })

    } else if (password == null || password == "") {
      wx.showToast({
        title: "密碼不能為空",
        icon: 'none',
        duration: 1500
      })
    } else {
      wx.request({

        url: getApp().globalData.urlPath + "sysUser/login",
        method: "POST",
        data: {
          username: username,
          password: password
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function(res) {
          console.log(res.data);
          if (res.statusCode == 200) {

            //訪問正常
            if (res.data.code == "000000") {
              wx.showToast({
                title: "登陸成功",
                icon: 'success',
                duration: 2000,
                success: function() {
                  wx.navigateTo({
                    url: '../manage/manage'
                  })

                  wx.setStorage({
                    key: 'userId',
                    data: res.data.user.userCode
                  })

                  wx.setStorage({
                    key: 'userName',
                    data: res.data.user.userName
                  })
                  console.log("test:" + wx.getStorageSync('userName'));
                }
              })

            } else if (res.data.code == "111111") {
              wx.showToast({
                title: "密碼錯誤",
                icon: 'none',
                duration: 1500
              })
            } else {
              wx.showToast({
                title: "該用戶不存在",
                icon: 'none',
                duration: 1500
              })
            }
          } else {

            wx.showLoading({
              title: '系統異常',
              fail
            })

            setTimeout(function() {
              wx.hideLoading()
            }, 2000)
          }

        }
      })
    }

  }
})

關於login.js,主要是寫通信邏輯的,與咱們平時寫js差異並不大,唯一不同的就是api長得不樣罷了。

關於其中的getApp().globalData.urlPath,相當於全局變量,不用我每次都寫一大串https之類的。

表單校驗的效果如圖:

 

代碼說明:

顯示消息提示框(相當於js的alert提示):

wx.showToast({
  title: "郵箱有誤",
  icon: 'none',
  duration: 1500
})

獲取input屬性為name的值(相當於js中form.email.value,前提是這個表單name要為form,且form中的input要存在一個name=”email”)

e.detail.value.email;

跳轉代碼(相當於window.location.href):

wx.navigateTo({
 url: '../manage/manage'
})

至於wx.request,我想只要是寫過ajax的,都很好理解。

login.json:

{
  "usingComponents": {}
}

關於這個login.json有什么用,我唯一想到的是頁面的title(其實相當於html中的title)

lgoin.wxml:

<view class='container'>
  <view class='header'>
    <text>acs系統</text>
  </view>
    <view>
    <text>\n</text>
  </view>
  <view class='header'>
  </view>
  <form bindsubmit="formSubmit">
    <view class='section'>
      <text>用戶名:</text>
      <input type='text' name="email" placeholder='請輸入郵箱' />
    </view>
    <view class='section'>
      <text>密碼:</text>
      <input password='password' name="pwd" placeholder='請輸入密碼' />
    </view>
    <view class='button'>
      <button type='primary' form-type='submit'>登錄</button>
      <text>\n</text>
       <view bindtap='register' class="register">注冊</view>
    </view>
  </form>

</view>

wxml相當於視圖(如html或者模板語言(jsp、volocity、freemarker、beetl等))
視圖除了可以寫一些標簽之類的,還可以寫一些邏輯判斷。后面會講到的。

login.wxss:

/* pages/login/login.wxss */
form{
  width: 310px;
  height: 240px;
  line-height: 40px;
  /* border: 1px solid red;  */
}
input{
  border: 1px solid #ccc;
  width: 310px;
  height: 40px;
}
.button{
  margin-top: 20px;
}
.header text{
  font-size: 25px;
  color: #666;
}
form text{
  font-size: 20px;
  color: #666;
}
.register{
color:black;
display: block;
width: 310px;
height: 40px;
border: 1px solid #ccc;
text-align: center;
}

這個wxss就相當於css,定義視圖的樣式,決定視圖長什么樣(好看不好看)

關於微信小程序網絡通信,更多信息可以參考官方文檔:
wx.request


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM