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) { },
})
}

微信小程序干货的更多相关文章

  1. 微信小程序源码推荐

    wx-gesture-lock  微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...

  2. 微信小程序案例大全

    微信小程序demo:足球,赛事分析 小程序简易导航 小程序demo:办公审批 小程序Demo:电魔方 小程序demo:借阅伴侣 微信小程序demo:投票 微信小程序demo:健康生活 小程序demo: ...

  3. 微信小程序踩坑集合

    1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=1476434678461 2:简易教程:https://mp.weixin.qq.com/debu ...

  4. 微信小程序源码案例大全

    微信小程序demo:足球,赛事分析 小程序简易导航 小程序demo:办公审批 小程序Demo:电魔方 小程序demo:借阅伴侣 微信小程序demo:投票 微信小程序demo:健康生活 小程序demo: ...

  5. 微信小程序实例源码大全2

    wx-gesture-lock  微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...

  6. 微信小程序项目实例

    目前为止最全的微信小程序项目实例 2018年03月20日 11:38:28 Happy王子乐 阅读数:4188   wx-gesture-lock  微信小程序的手势密码 WXCustomSwitch ...

  7. 转:目前为止最全的微信小程序项目实例

    wx-gesture-lock  微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...

  8. 这是一篇满载真诚的微信小程序开发干货

    1月9日零点刚过,张小龙与团队正式发布微信小程序.它究竟能在微信8.5亿用户中牵动多少人,现在还很难说.但对于创业者来讲,小程序无疑带来了新契机,以及服务“上帝”们的新方式. 从今天起,只要开发者登录 ...

  9. 【腾讯Bugly干货分享】打造“微信小程序”组件化开发框架

    本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/2nQzsuqq7Avgs8wsRizUhw 作者:Gc ...

随机推荐

  1. ACM学习历程——POJ3321 Apple Tree(搜索,线段树)

          Description There is an apple tree outside of kaka's house. Every autumn, a lot of apples will ...

  2. 用PCA降维 (Principal Component Analysis,主成分分析)

    参考资料:Mastering Machine Learning With scikit-learn 降维致力于解决三类问题.第一,降维可以缓解维度灾难问题.第二,降维可以在压缩数据的同时让信息损失最 ...

  3. mina2中的线程池

    一.Mina中的线程池模型 前面介绍了Mina总体的层次结构,那么在Mina里面是怎么使用Java NIO和进行线程调度的呢?这是提高IO处理性能的关键所在.Mina的线程调度原理主要如下图所示: A ...

  4. Ternary Calculation

    Ternary Calculation Time Limit : /2000ms (Java/Other) Memory Limit : /65536K (Java/Other) Total Subm ...

  5. WCF IIS部署

    创建WCFHost应用程序 Iservice.cs using System; using System.Collections.Generic; using System.Linq; using S ...

  6. 反射设置当前窗体所有控件的Text

    在我们编程的时候,有时需要动态的获取当前窗体控件的Text,但是又不能一个一个控件的设置,这个时候可以通过反射来动态设置. 第一步:先建立一个类来保存控件的Text信息. public class C ...

  7. xgene:肿瘤相关基因 EGFR,,Her2,,TP53,,ALK

    EGFR: “Epidermal growth factor receptor”,表皮生长因子受体.别名:ErbB1,或 HER1 EGFR是ErbB基因家族的成员之一.ErbB基因家族包括了:EGF ...

  8. 《Java多线程编程核心技术》读后感(十二)

    类ThreadLocal的使用 主要解决的是每个线程绑定自己的值,可以将ThreadLocal类比喻成全局存放数据的盒子,盒子中可以存储每个线程私有数据. 类ThreadLocal解决的是变量在不同线 ...

  9. 深度解析VC中的消息传递机制

    摘要:Windows编程和Dos编程,一个很大的区别就是,Windows编程是事件驱动,消息传递的.所以,要学好Windows编程,必须 对消息机制有一个清楚的认识,本文希望能够对消息的传递做一个全面 ...

  10. conntrack-tools使用

    基础用法 系统配置 ### 开启流数据包统计(packets和bytes) # echo "net.netfilter.nf_conntrack_acct=1" >> ...