微信小程序干貨


1.獲取text文本框輸入的信息

  wxml代碼

 

<view class="weui-cells">
  <view class="weui-cell weui-cell_input">
    <view class="weui-cell__bd">
      <input class="weui-input" bindinput="changepapertitle" maxlength="100" placeholder="請輸入問卷標題(最多100個字)" value='{{papertitle}}' />
    </view>
  </view>
</view>

 

 

 

 后端js

 

划重點:通過bindinput事件,在后端能夠獲取到輸入值

 

2.獲取同一個控件的多個屬性

wxml代碼

<input type='text' style='width:200px' bindinput="ratiotxtchange"  data-qid='{{item.qid}}'  id="{{dqdata.dqid}}"  placeholder='其他'></input>

js代碼

 

//單選其他選項輸入
  ratiotxtchange:function(e){
    debugger;
    var id = e.currentTarget.id; //選項ID
    var qid = e.currentTarget.dataset.qid;//問題ID
    var value = e.detail.value; //單選框的值
    this.data.radtxts[qid] =id+"|"+ value;
    this.data.tschecks["A"+qid] = id + "|" + value;//存入特殊選項的ID

  }

 

划重點:前端通過設置data-xx的信息,后端用

e.currentTarget.dataset.xx 獲取其中的值,
此方法可以獲取同一個控件的多個屬性,對處理某些復雜點的邏輯,比較有用

3.微信小程序AJAX請求
    wx.request({
      url: posturl + "/Form/AddAnswerPaper",
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        "paperid": paperid, //問卷ID
        "openid": getApp().globalData.openid, //當前登錄人
        "rich": JSON.stringify(rich),
        "txts": JSON.stringify(txts),
        "redio": JSON.stringify(rads),
        "checks": JSON.stringify(checks),
        "img": JSON.stringify(imgs),
        "addresses": JSON.stringify(addresses),

      },
      success: function (rdata) {
        if (rdata.data.result == true) {

          that.setData({
            modalHidden: !that.data.modalHidden
          })
         
        } else {
          wx.showToast({
            title: "保存失敗",
            icon: 'loading',
            duration: 3000
          })
        }
      }
    })
 
        

4.后端獲取微信小程序openid

 
        
        /// <summary>
        /// 獲取微信用戶OPENID
        /// </summary>
        /// <returns></returns>
        public string QueryOpenId()
        {
            seesionmodel m = new seesionmodel();
            try
            {
                string code = Request["code"];
                string Appid = ConfigurationSettings.AppSettings["Appid"];
                string AppSecret = ConfigurationSettings.AppSettings["AppSecret"];
                string html = string.Empty;
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream ioStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(ioStream, Encoding.UTF8);
                html = sr.ReadToEnd();
                sr.Close();
                ioStream.Close();
                response.Close();
                m = JsonConvert.DeserializeObject<seesionmodel>(html);
                return m.openid;
            }
            catch (Exception ex)
            {
                logger.Debug(ex.Message);
                m.openid = "獲取OpenID失敗";
            }
          
            return JsonConvert.SerializeObject(m);


        }
 
        
    public class seesionmodel
    {
        public string session_key { get; set; }
        public string expires_in { get; set; }
        public string openid { get; set; }
    }

 通過后端獲取微信用戶唯一的ID,一是提高安全性,二是可以避免授權彈框。

 

5.微信小程序彈出可輸入的對話框

 

實例:點擊紅線,彈出可輸入對話框,然后保存。

 


 文本框部分代碼:
   
<view class="p">
      <view bindtap='namechange' style='width:120px;margin:0 auto'>
        <input type='text' class='txtname' value='{{RealName2}}' disabled='disabled' placeholder='請輸入您的姓名' />
      </view>
 </view>


彈出框部分代碼:

<modal hidden="{{hiddenmodalput}}" title="請輸入" confirm-text="提交" bindcancel="cancel" bindconfirm="confirm">
    <input type='text' bindinput='nameinput' value='{{RealName}}'  class='txtname' placeholder="請輸入您的名字" auto-focus/>
</modal>
 
        
var posturl = getApp().globalData.posturl;
Page({
  data: {
    IcreateNum: 0,
    IJoinNum: 0,
    nickName:"",
    hiddenmodalput:true,
    RealName:"",
    RealName2: ""
  },
  onLoad: function(options) {
    var realname= wx.getStorageSync('RealName');
    if(realname!=""){
      this.setData({
        RealName2: realname
      })
      console.log("從緩存讀取姓名");
    }else{
      var openid = getApp().globalData.openid;
      var that=this;
      console.log("從數據庫讀取姓名");
      wx.request({
        url: posturl + "/Form/QueryRealNameByOpenId", //自己的服務接口地址  
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {

          "OpenID": openid
        },
        success: function (data) {
          that.setData({
            RealName2: data.data,

          });
          wx.setStorageSync('RealName', data.data);

        }
      });
    }
  },
  //單擊名字
  namechange:function(e){
    console.log("444");
    var RealName2 = this.data.RealName2;
    this.setData({
      hiddenmodalput: false,
      RealName: RealName2
    })
  },
  cancel:function(e){
    this.setData({
      hiddenmodalput: true
    })
  },
  //獲取姓名
  nameinput:function(e){
    let name = e.detail.value;
    console.log(name);
    this.setData({
      RealName: name
    })
  },
  //提交姓名
  confirm:function(e){
    var Name = this.data.RealName;
    var openid = getApp().globalData.openid; //唯一標識
    var RealName = this.data.RealName;

    var that=this;
    wx.request({
      url: posturl + "/Form/UpdateRealNameByOpenId", //自己的服務接口地址  
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        "RealName": RealName,
        "OpenID": openid
      },
      success: function (data) {
        if (data.data.result == true) {

          that.setData({
            hiddenmodalput:true,
            RealName2:RealName
          });
          wx.setStorageSync('RealName', RealName);
        } else {
          wx.showModal({
            title: '錯誤提示',
            content: '修改姓名失敗',
            showCancel: false,
            success: function (res) { }
          })
        }


      }
    });

  },
  onReady: function() {

      
  },
  onShow: function() {
    // 頁面顯示
    // 頁面初始化 options為頁面跳轉所帶來的參數
    this.queryNumIcreate();
    this.queryNumIJoin();
  },
  onHide: function() {
    // 頁面隱藏
  },
  onUnload: function() {
    // 頁面關閉
  },
  
  userNickNameclick:function(){
    console.log("3333");
  }
})

6.微信小程序上傳圖片

 
        

wxml

      <view class="uploader-text" bindtap="chooseImage2">添加圖片</view>

js

chooseImage2: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
      count: 1, // 最多可以選擇的圖片張數
      success: function (res) {


        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片  
        var tempFilePaths = res.tempFilePaths;
        //啟動上傳等待中...  
        wx.showToast({
          title: '正在上傳...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })

        wx.uploadFile({
          url: posturl + '/Form/uploadfilenew',
          filePath: tempFilePaths[0],
          name: 'uploadfile_ant',
          formData: {
            'imgIndex': 0
          },
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: function (res) {

            tempFilePaths = [];
            var saveurl = posturl + JSON.parse(res.data).Url.replace("..", "");
            tempFilePaths.push(saveurl);
            that.setData({
              files2: [],
            });
            // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
            that.setData({

              files2: that.data.files2.concat(tempFilePaths)
            });

            wx.hideToast();
          },
          fail: function (res) {
            wx.hideToast();
            wx.showModal({
              title: '錯誤提示',
              content: '上傳圖片失敗',
              showCancel: false,
              success: function (res) { }
            })
          }
        });


      }
    })
  },

 

 c#

  /// <summary>
        /// 上傳文件、圖片
        /// </summary>
        /// <returns></returns>
        public ContentResult UploadFileNew()
        {
            UploadFileDTO model = new UploadFileDTO();
            try
            {
                HttpPostedFileBase file = Request.Files["uploadfile_ant"];
                if (file != null)
                {
                    //公司編號+上傳日期文件主目錄  
                    model.Catalog = DateTime.Now.ToString("yyyyMMdd");
                    model.ImgIndex = Convert.ToInt32(Request.Form["imgIndex"]);

                    //獲取文件后綴  
                    string extensionName = System.IO.Path.GetExtension(file.FileName);

                    //文件名  
                    model.FileName = System.Guid.NewGuid().ToString("N") + extensionName;

                    //保存文件路徑  
                    string filePathName = Server.MapPath("~/images/") + model.Catalog;
                    if (!System.IO.Directory.Exists(filePathName))
                    {
                        System.IO.Directory.CreateDirectory(filePathName);
                    }
                    //相對路徑  
                    string relativeUrl = "../images";
                    file.SaveAs(System.IO.Path.Combine(filePathName, model.FileName));

                    //獲取臨時文件相對完整路徑  
                    model.Url = System.IO.Path.Combine(relativeUrl, model.Catalog, model.FileName).Replace("\\", "/");
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
        }

6.微信小程序點擊圖片預覽

 wxml

   <image wx:if='{{DescribeImg!=""&&DescribeImg!=null}}' style='width:400rpx;height:400rpx' src='{{DescribeImg}}' bindtap='previewImg'></image> 

js

//圖片放大
  previewImg: function (e) {

    var img = this.data.DescribeImg;//圖片網址
    var ary = new Array();
    ary.push(img);
    wx.previewImage({
      current: ary[0],     //當前圖片地址
      urls: ary,//路徑集合,必須是數組
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  }

 


免責聲明!

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



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