微信小程序干货
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) { },
})
}
微信小程序干货的更多相关文章
- 微信小程序源码推荐
wx-gesture-lock 微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...
- 微信小程序案例大全
微信小程序demo:足球,赛事分析 小程序简易导航 小程序demo:办公审批 小程序Demo:电魔方 小程序demo:借阅伴侣 微信小程序demo:投票 微信小程序demo:健康生活 小程序demo: ...
- 微信小程序踩坑集合
1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=1476434678461 2:简易教程:https://mp.weixin.qq.com/debu ...
- 微信小程序源码案例大全
微信小程序demo:足球,赛事分析 小程序简易导航 小程序demo:办公审批 小程序Demo:电魔方 小程序demo:借阅伴侣 微信小程序demo:投票 微信小程序demo:健康生活 小程序demo: ...
- 微信小程序实例源码大全2
wx-gesture-lock 微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...
- 微信小程序项目实例
目前为止最全的微信小程序项目实例 2018年03月20日 11:38:28 Happy王子乐 阅读数:4188 wx-gesture-lock 微信小程序的手势密码 WXCustomSwitch ...
- 转:目前为止最全的微信小程序项目实例
wx-gesture-lock 微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...
- 这是一篇满载真诚的微信小程序开发干货
1月9日零点刚过,张小龙与团队正式发布微信小程序.它究竟能在微信8.5亿用户中牵动多少人,现在还很难说.但对于创业者来讲,小程序无疑带来了新契机,以及服务“上帝”们的新方式. 从今天起,只要开发者登录 ...
- 【腾讯Bugly干货分享】打造“微信小程序”组件化开发框架
本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/2nQzsuqq7Avgs8wsRizUhw 作者:Gc ...
随机推荐
- UOJ_21_【UR #1】缩进优化_数学
UOJ_21_[UR #1]缩进优化_数学 题面:http://uoj.ac/problem/21 最小化$\sum\limits{i=1}^{n}a[i]/x+a[i]\;mod\;x$ =$\su ...
- Restore Points 制定回退方案
Restore Points 制定回退方案 背景:Flashback Database 和 restore points 都可以提供一个基于时间点的回滚. 理论:1) Normal Restore P ...
- poj2228Naptime——环形DP
题目:http://poj.org/problem?id=2228 dp[i][j][0/1]表示前i小时中第j小时睡(1)或不睡(0)的最优值: 注意第一个小时,若睡则对最终取结果有要求,即第n个小 ...
- 【opencv学习笔记四】opencv3.4.0图形用户接口highgui函数解析
在笔记二中我们已经知道了,在highgui文件夹下的正是opencv图形用户接口功能结构,我们这篇博客所说的便是D:\Program Files\opencv340\opencv\build\incl ...
- Python的subprocess子进程和管道进行交互
在很久以前,我写了一个系列,Python和C和C++的交互,如下 http://blog.csdn.net/marising/archive/2008/08/28/2845339.aspx 目的是解决 ...
- eclipse必备快捷键
1.[ Ctrl + Shift+ P ],查找括号的开始和闭合 2.[ALT+/],这个快捷键应该没有人不知道 3.[Ctrl+O],显示类中方法和属性的大纲,能快速定位类的方法和属性,在查找Bu ...
- Primer回顾 标准库类型
string类型的输入操作符: 1.读取并忽略开头所有的空白字符(如空格,换行符,制表符). 2.读取字符直至再次遇到空白字符,读取终止. 用getline读取整行文本 getline.接受两个参 ...
- (一)新建一个javaweb项目
一.为了不影响其他项目,可以重新选择一个新的工作目录:swith workspace 二.为了尽可能统一项目,所使用的编程环境,包括:Tomcat.JRE都是项目组自己的,所以在新建项目的时候要注意选 ...
- Centos 6.5 下Nginx安装部署https服务器
一般我们都需要先装pcre, zlib,前者为了重写rewrite,后者为了gzip压缩.1.选定源码目录选定目录 /usr/local/cd /usr/local/2.安装PCRE库cd /usr/ ...
- win10怎样彻底关闭windows Defender
首先,我们在电脑中需要进入注册表编辑器进行修改,win10电脑进入windows Defender可以有两种方式,第一种是通过电脑自带的小娜进入,第二种则是常规的win加r. 不管使用哪种方式,首 ...