微信小程序干货
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 ...
随机推荐
- 【运维程序】简单的命令控制器(支持定时命令执行、重复定时任务命令和进程管理,开发这个小程序主要是为了方便管理服务进程)【个人github项目】
一.前言: command-controller 一个运维程序,简单的命令控制器(支持定时命令执行和重复定时命令,开发这个程序主要是为了方便管理服务进程) 本来是要用python做的,但是之前做ffm ...
- TTY,Console以及Terminal
TTY可以理解是一种终端显示.可以在/dev文件夹看到多个tty开头的文件,可以通过alt+Fn(n=1~6)来进行切换.这个是不是和GUI场景下的多个Terminal窗口是一致的呢? 伪TTY是指一 ...
- 【转】有的共享软件赚了一百万美元,而为什么你没有?&&我的软件推广成功之路
有的共享软件赚了一百万美元,而为什么你没有? 转自:http://blog.csdn.net/wangjiwei2010/article/details/1267044 译:DreamGoal 原作: ...
- Python3解leetcode Symmetric Tree
问题描述: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). ...
- POJ1523(割点所确定的连用分量数目,tarjan算法原理理解)
SPF Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 7406 Accepted: 3363 Description C ...
- maven+eclpse+jmeter+jenkis
1.maven配置:http://www.cnblogs.com/AlanLee/p/6133189.html 2.在eclipse中创建maven项目:https://jingyan.baidu.c ...
- IoT:目录
ylbtech-IoT:目录 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 6.返回顶部 作者:ylbtech出处:http://ylbtech.c ...
- shell 脚本学习之一 ------let,echo,变量
转自:http://blog.chinaunix.net/uid-26827001-id-3154024.html 首先看到好多以这样开头的 #!/bin/bash 这个是告诉系统 解释此脚 ...
- ng2自定义管道
一.管道的作用及本质 作用:数据处理 本质:公用的方法 二.定义管道组件 //summary.pipe.tsimport { Pipe, PipeTransform } from '@angular/ ...
- cordova之旅之初识
emmmm, 一直徘徊在移动端采用什么技术比较好,一直也没有找到,让我为了一个移动端而去学习一波react全家桶是不现实的操作,反观自己的技术栈,通过长时间的对比和剖析找到了入口点,不管了先会写再说吧 ...