Home > Article > WeChat Applet > C# development of WeChat portals and applications--Experience summary of WeChat H5 page development
When we develop WeChat pages, we need to use a lot of various presentation effects. Generally, we can use Boosttrap effects to design different pages. However, the WeChat team also provides many resources in this area, including JSSDK interfaces, and Weui's page style and related function pages provide us with great convenience. This article is a summary of some functions on some H5 WeChat application pages that I have made. I hope it can provide some help to everyone.
1) JSSDK
WeChat JS-SDK is provided by WeChat public platform for web developers based on WeChat Web Development Kit. By using WeChat JS-SDK, web developers can use WeChat to efficiently use the capabilities of mobile phone systems such as taking pictures, selecting pictures, voice, and location. At the same time, they can directly use WeChat's unique capabilities such as sharing, scanning, coupons, and payment. , providing WeChat users with a better web experience.
The interface categories currently supported by JSSDK include the following categories: basic interface, sharing interface, image interface, audio interface, intelligent interface, device information, geographical location, shake peripherals, interface operation, WeChat scan , WeChat store, WeChat coupons, WeChat payment, with the integration of all WeChat functions, it is estimated that more interfaces will be opened one after another.
2) WeUI and Jquery WeUI
WeUI is a set of basic style libraries consistent with WeChat’s native visual experience. It is designed by the WeChat official design team Tailor-made design for web development within WeChat can make users’ usage perception more unified. Using WeUI in WeChat web development has the following advantages:
The same visual effect as the WeChat client makes it easier for all WeChat users to use your website
Convenient access and quick use, reducing development and design costs
WeChat design team carefully created, clear, concise and generous
This style library currently includes various elements such as button, cell, dialog, progress, toast, article, icon, etc., and has been open sourced on GitHub. Visit http://www.php.cn/ or scan the QR code on WeChat to preview.
jQuery WeUI uses the official WeUI CSS code and provides jQuery/Zepto version of the API implementation. Compared with the official WeUI, JQuery WeUI has made some functional extensions and enriched the interface design and related functions. Therefore, we can consider developing the page directly based on JQuery WeUI.
In some of my previous cases, We UI style was used to design the functions of many WeChat H5 pages, including WeChat payment pages, sign-in pages, etc.
For example, the WeChat payment page is as follows:
and the effect of the check-in page is as follows.
Of course, we can add many pages with the same color and style as WeChat according to business needs. This is the benefit of using the consistency of the interface experience brought by WeUI style. .
This article mainly introduces the experience summary of WeChat H5 page development. It is mentioned above that JSSDK and WeUI are used to develop H5 pages of WeChat applications, so the following related effects are processed using these technologies.
In some cases, we may need the user to open the connection only on the WeChat browser and not use other browsers to open the connection. In addition, the acquisition of some user identity information also needs to be redirected through the WeChat browser. Otherwise, errors will occur when using other browsers. Therefore, it is sometimes a common practice to determine whether it is a WeChat browser.
There are two ways to determine whether it is a WeChat browser. One is to use JS scripts on the front end to process, and the other is to use background C# code to determine and process. Both methods can achieve the purpose.
Use JS code to achieve the code and effect as shown below.
//判断是否在微信中打开 function isWeiXin() { var ua = window.navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == 'micromessenger') { return true; } else { return false; } }
The page output processing is as follows.
$(function () { var isWeixin = isWeiXin(); if (isWeixin) { $("#weixin").html(window.navigator.userAgent); //请在微信中打开该页面 } var display = "是否在微信浏览器中打开:"; display += isWeixin ? "是" : "否"; $("#isWeixin").html(display); });
If it is a page link that is normally redirected using WeChat, then it will prompt as :yes.
As mentioned just now, you can also use C# background code to determine whether it is in the browser. Under normal circumstances, we can determine the user's browser and then redirect. If the user is indeed a WeChat browser, continue Process it later, otherwise the user will be redirected to the prompt page.
/// <summary> /// 检查是否微信中打开,否则重定向 /// </summary> /// <returns></returns> protected string CheckBrowser() { bool passed = false; string userAgent = Request.UserAgent; passed = userAgent.ToLower().Contains("micromessenger"); if (!passed) { var type = "warn"; var message = "请在微信中打开该页面"; var url = string.Format("{0}/H5/info?type={1}&message={2}", ConfigData.WebsiteDomain, type, message); return url; } return null; }
We can make the judgment at the beginning of the function.
//如果不是微信浏览器,则返回错误页面 var checkUrl = CheckBrowser(); if (!string.IsNullOrEmpty(checkUrl)) return Redirect(checkUrl);
If a non-WeChat browser opens the page link, the redirected page effect is as follows.
The same as the regular web page functions, when we design the WeChat page application, many The data also comes from dictionary data, and they need to be dynamically bound to the page. The JQuery WeUI of the WeChat page provides some display effects of list dictionary data as shown below.
This regular data binding is as shown below, as shown in the following JS code.
$("#job").select({ title: "选择职业", items: ["法官", "医生", "猎人", "学生", "记者", "其他"], onChange: function(d) { console.log(this, d); }, onClose: function() { console.log("close"); }, onOpen: function() { console.log("open"); }, });
You can also use collection objects for assignment processing, as shown in the following JS code.
$("#in").select({ title: "您的爱好", multi: true, min: 2, max: 3, items: [ { title: "画画", value: 1, description: "额外的数据1" }, { title: "打球", value: 2, description: "额外的数据2" } ], beforeClose: function(values, titles) { if(values.indexOf("6") !== -1) { $.toast("不能选打球", "cancel"); return false; } return true; }, onChange: function(d) { console.log(this, d); } });
Based on the above JS script, we choose the latter and use Ajax technology to fill in the data, so that the background dictionary can be dynamically obtained data, and perform page binding operations.
For convenience, we can design a public function for data dictionary binding processing, as shown below.
//绑定字典内容到指定的控件 function BindDictItem(ctrlName, dictTypeName, onChange, onClose, onOpen) { var url = '/h5/GetDictJson?dictTypeName=' + encodeURI(dictTypeName); //获取Ajax的内容,并放到items集合 var control = $('#' + ctrlName); var items = []; $.ajax({ type: 'GET', url: url, //async: false, //同步 dataType: 'json', success: function (data) { control.empty();//清空下拉框 //把JSON集合加到数组里面 $.each(data, function (i, item) { items.push({ title: item.Text, value: item.Value }); }); //设置显示列表 control.select({ title: "选择" + dictTypeName, items: items, onChange: onChange, onClose: onClose, onOpen: onOpen }); }, error: function (xhr, status, error) { $.toast("操作失败" + xhr.responseText); //xhr.responseText } }); }
Then when we bind dictionary data, we only need to call this function to easily implement the data dictionary binding operation. .
$(function () { BindDictItem("Status", "设备状态"); BindDictItem("Dept", "科室"); BindDictItem("Building", "建筑物"); BindDictItem("Floor", "楼层"); BindDictItem("Special", "特殊情况"); });
Let’s look at how to open the corresponding connection in WeChat. The effect of dictionary binding is as follows.
#We can maintain the data dictionary in the WeChat background to perform real-time data updates.
In many pages, we need to display rich pictures, and we need to combine them with WeChat The image preview function interface allows us to open the image to facilitate zoom processing operations. So how to use the image preview interface of WeChat JSSDK?
First we need to introduce the style class library of Jquery WeUI and the JS files required by JSSDK, as shown below.
<script src="~/Content/wechat/jquery-weui/lib/jquery-2.1.4.js"></script> <script src="~/Content/wechat/jquery-weui/js/jquery-weui.js"></script> <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
Then initialize the JSSDK API script on the page, as shown in the following code.
var appid = '@ViewBag.appid'; var noncestr = '@ViewBag.noncestr'; var signature = '@ViewBag.signature'; var timestamp = '@ViewBag.timestamp'; wx.config({ debug: false, appId: appid, // 必填,公众号的唯一标识 timestamp: timestamp, // 必填,生成签名的时间戳 nonceStr: noncestr, // 必填,生成签名的随机串 signature: signature, // 必填,签名,见附录1 jsApiList: [ 'checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage' ] }); //所有准备好后 wx.ready(function () { });
The Join Us page contains two parts of pictures, one is the equipment nameplate picture, and the other is other accessory pictures, we respectively Display, as shown in the following HTML code.
<p class="weui_cells_title"><h3>铭牌图片</h3></p> <p class="weui_cells"> <p class="weui_cell"> <p id="previewImage"> @for (var i = 0; i < ViewBag.mainList.Count; i++) { <img id='mainPic_@i' src='@ViewBag.mainList[i]' alt="铭牌图片" style="height:auto;width:100%" /> } </p> </p> </p> <p class="weui_cells_title"><h3>其他图片</h3></p> <p class="weui_cells"> <p class="weui_cell"> <p id="previewImage2"> <p class="weui-row"> @for (var i = 0; i < ViewBag.otherList.Count; i++) { <p class="weui-col-50"> <img id='otherPic_@i' src='@ViewBag.otherList[i]' alt="其他图片" style="height:auto;width:100%" /> </p> } </p> </p> </p> </p>
These codes build many picture controls, which are the original HTML picture controls. If you only do this, then you can only Utilize the effect of web pages, but cannot use WeChat browser to preview pictures, and have rich functions of zooming in and out.
In order to achieve the functions we say we need, certain processing needs to be done. A simple method is to design a JS function, and then use the JS function to implement the WeChat preview image function. The code is as follows.
function BindClick(selector) { document.querySelector(selector).onclick = function (event) { var imgArray = []; var curImageSrc = $(this).attr('src'); var oParent = $(this).parent(); if (curImageSrc && !oParent.attr('href')) { $(selector).each(function (index, el) { var itemSrc = $(this).attr('src'); imgArray.push(itemSrc); }); wx.previewImage({ current: curImageSrc, urls: imgArray }); } } } BindClick('#previewImage img'); BindClick('#previewImage2 img');
这个函数的做法,是参考网上一个大牛的做法,不过这样做存在一个问题,图片如果有多张的话,那么需要点击第一张图片才能开始预览,不能点击其他几张开始。
为了改进这个缺点,我们可以可以利用Razor的模板实现我们需要的代码生成,如下所示集合了Razor模板生成JS代码,实现了我们所需要JS代码的生成。
var urls = []; @foreach (var url in ViewBag.mainList) { <text>urls.push('@url');</text> } @for (var i = 0; i < ViewBag.mainList.Count; i++) { <text> document.querySelector('#mainPic_@i').onclick = function () { wx.previewImage({ current: $(this).attr("src"),//urls[@i], urls: urls }); }; </text> } var urlsOther = []; @foreach (var url in ViewBag.otherList) { <text>urlsOther.push('@url');</text> } @for (var i = 0; i < ViewBag.otherList.Count; i++) { <text> document.querySelector('#otherPic_@i').onclick = function () { wx.previewImage({ current: $(this).attr("src"),//urls[@i], urls: urlsOther }); }; </text> }
JS代码的生成后的代码如下所示.
var urls = []; urls.push('http://www.iqidi.com/UploadFiles/设备铭牌图片/TIzMZl04X1iqkHMP44hXFHjQ-yyvrxS-tgwgzMGfwe9AUMTxKohcVC6w6O.jpg'); document.querySelector('#mainPic_0').onclick = function () { wx.previewImage({ current: $(this).attr("src"),//urls[0], urls: urls }); }; var urlsOther = []; urlsOther.push('http://www.iqidi.com/UploadFiles/设备铭牌图片/lJk_LNwxTGfL5SNpmJwWyfyBONa2JRO7uzu3PJV3aGsrilPPHY2r-ymU00.jpg'); document.querySelector('#otherPic_0').onclick = function () { wx.previewImage({ current: $(this).attr("src"),//urls[0], urls: urlsOther }); };
这样最终就可以实现我们所需要的效果了,当然多张图片也不会有任何的问题。
更多C#开发微信门户及应用--微信H5页面开发的经验总结 相关文章请关注PHP中文网!