Summary of experience in developing H5 page control based on Jquery WeUI

When WeChat develops H5 pages, it often develops the interface effect based on WeUI or Jquery WeUI. Because I like to use JQuery on Asp.net's Web interface, I prefer to use jQuery.WeUI, this article combines official cases with the actual development experience of their own projects to analyze and summarize the interface controls designed in the H5 page development process one by one, in order to provide you with useful reference in the H5 page development process.

This essays continues with the last one, " Summary of experience in developing H5 page control based on Jquery WeUI for Microsoft (1) "To introduce the contents of other sections.

7) Bar code, 2-D code generation

When we do some scanner operations, we may need to generate some URL s based on some parameters, and then generate a two-dimensional code to make it easy for mobile phone to scanner code directly, or to read the barcode for some barcode devices, so the two cases together are the scene of two-dimensional code and barcode processing.

This scenario is needed, for example, in the prescription information display below.

The address used by QRCode is: https://github.com/davidshimjs/qrcodejs 

The address used by the barcode JsBarcode is: https://github.com/lindell/JsBarcode

Before using, we introduced the required JS library files for qrcodejs and JsBarcode.

<script src="~/Content/JQueryTools/qrcodejs/qrcode.min.js"></script>
<script src="~/Content/JQueryTools/JsBarcode/dist/JsBarcode.all.min.js"></script>

Processing scripts for two-dimensional and bar codes are simple, as shown in the JS code below.

//bar code
JsBarcode("#barcode", "@ViewBag.Info.PrescriptionNo", {
  format: "CODE128",
  lineColor: "#0aa",
  height: 50,
  displayValue: false
});

//QR code
var url = '@ViewBag.WebsiteDomain/h5/PrescriptionDetail?id=@ViewBag.Info.ID';
var qrcode = new QRCode(document.getElementById("qrcode"), {
    text: url, //"@ViewBag.Info.PrescriptionNo",
    width: 128,
    height: 128,
    colorDark : "#000000",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});

It's a good way to use scripting.

 

8) Ajax/Post/Get related processing of JQuery

In many of our previous case codes, JQuery's Ajax/Post/Get/getJSON functions are used, and they can often be substituted for each other, but the differences are only a small part.

The $.get() method uses GET for asynchronous requests, and its syntax is: $.get (url [, data] [, callback]).The code below shows.

$.getJSON() is set specifically for ajax to obtain json data and supports cross-domain invocation in the form of getJSON(url,[data],[callback]).

var flowUsers = [];
var url = '/qyh5flow/GetCorpUser';
$.getJSON(url, function (data) {
    $.each(data, function (i, item) {
        flowUsers.push({
            title: item.name, value: item.userid
        });
    });
    $("#txtSelectSignUser").select({
        title: "Select Signing Person",
        items: flowUsers,
        multi: true,
        //min: 2,
        //max: 3,
    });
});

The $.get() and $.getJSON() methods, which have one more JSON conversion object to process the returned data than the former, require the following code for JSON conversion.

 var data = $.parseJSON(json);

The $.post() method uses POST for asynchronous requests, and its syntax structure is: $.post(url,[data],[callback],[type]), which is submitted using POST for operations relative to $.get().

The type:type is the requested data type, which can be html,xml,json, etc. If we set this parameter to: json, the returned format is json, if not set, it is string like the returned format of $.get().

The following code is for data submission using the $.post() function. Note that we also need to use $.parseJSON for processing JSON transformation objects with return values.

$.post(url, postData, function (json) {
    //Escape JSON As an object
    var data = $.parseJSON(json);
    if (data.Success) {
        $.toptip("Delete successful!", 'success');

        //Find the corresponding control on the interface ID,Remove Control
        RemoveImg();
    }
    else {
        $.toast("operation failed:" + data.ErrorMessage, "forbidden");
    }
});

$.ajax() is an Ajax encapsulation commonly used in jquery with the syntax format: $.ajax(options), where options is an object type that specifies the specific parameters for this Ajax call.

Typically when working with FormData objects, I prefer to work with $.ajax to make the settings more flexible.

//Submit form data and files
var url = "/qyH5Flow/PaymentSave?userid=@ViewBag.userid";
$.ajax({
    url: url,
    type: 'post',
    processData: false,
    contentType: false,
    data: formData,
    success: function (json) {
        //Escape JSON As an object
        var data = $.parseJSON(json);
        if (data.Success) {
            $.toast("Save successfully, please check the list interface later.");
        }
        else {
            $.toast("Save failed:" + data.ErrorMessage, "forbidden");
        }
    }
});

The various operations I have used in the case above can sometimes be replaced with each other, and different operation modes can be selected as needed.

 

9) Array object handling of JS scripts

Above we used various asynchronous operations, such as Ajax/Post/Get/getJSON for JQuery, which often involved traversing or inserting arrays.

JS arrays are powerful array objects that support a lot of complex operations. Operations on arrays are also one of the ways we often handle them.

For example, for returned data, we typically need to traverse the array and append it to the interface display one by one, using the $.each() function.

//Dynamic processing of picture bindings
$.getJSON("/Qyh5Flow/GetImageList2?attachGuid=" + info.AttachGUID, function (data) {
    $.each(data, function (i, item) {
        $("#imgAttach").append(`<img class='weui-uploader__file' src='${item.Text}' id='img_${item.Value}'/>`);
    });
});

Another common scenario for the $.each() function is the traversal of element collections based on the JQuery selector.

var itemCount = 0;
//Calculate the number of selected radio boxes
$("input[type='radio']:checked").each(function(){
    itemCount += 1;
});
//Check box to calculate one
var chkName = []
$("input[type='checkbox']:checked").each(function () {
    var name = $(this).attr('name');
    if (chkName.indexOf(name) < 0) {
        itemCount += 1;
        chkName.push(name);
    }
});

When we need to add objects, we need to use the push() function, sometimes in conjunction with the $.each() function.

var items = [];
$.each(data, function (i, item) {
    items.push({
        title: item.Text, value: item.Value
    });
});

Or, when performing element traversal queries, the code below shows.

//Build Selected List Content
var list = [];
//Calculate Radio Box
$("input[type='radio']:checked").each(function () {
    list.push($(this).val());
});
//Calculate check box
$("input[type='checkbox']:checked").each(function () {
    list.push($(this).val());
});

If we need to determine whether an object is in a collection or not, we use the $.inArray() function, as shown in the code below.

if ($.inArray(key, addKeyList) == -1) {
    addKeyList.push(key);
    addValueList.push(value);
    sendList.push({ key: key, value: value});

    $('#tagsToSend').addTag(value);
}

In addition, we need to understand how to remove individual or all collections for arrays, which uses the splice() function, as shown in the code below.

addKeyList.splice(i, 1);//Remove an object
addValueList.splice(i, 1);//Remove an object
sendList.splice(i, 1);//Remove an object

If you need to empty the array, the usual practice is to use the splice() function, as shown below.

//Empty User Selection
function ClearChoice() {
    $('#tagsToSend').importTags('');

    sendList.splice(0, sendList.length);//Departments, Labels, User Lists to Send
    addKeyList.splice(0, addKeyList.length);//Collection of keys
    addValueList.splice(0, addValueList.length);//Set of values
}

These are some of the methods we often use when working with data.

 

10) Query Instant List Display

Sometimes, we need to retrieve information from a database based on the query criteria, then display it in a list for selection, as shown in the following interface.

 

The picture above is my project, which retrieves drugs according to their phonetic codes or names and displays the returned data.

To use the search bar, we used the search bar style defined by WeUI of WeChat. Here is the search bar DIV layer defined by the interface, and the code below.

    <!--The search bar, similar to WeChat's native search bar, is used in common search scenarios.-->
    <div class="weui-search-bar" id="searchBar">
        <form class="weui-search-bar__form" onkeydown="if(event.keyCode==13) return false;">
            <div class="weui-search-bar__box">
                <i class="weui-icon-search"></i>
                <input type="search" class="weui-search-bar__input" id="searchInput" placeholder="search" required="">
                <a href="javascript:clear()" class="weui-icon-clear" id="searchClear"></a>
            </div>
            <label class="weui-search-bar__label" id="searchText" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);">
                <i class="weui-icon-search"></i>
                <span>Please enter the keywords you want to see</span>
            </label>
        </form>
        <a href="javascript:clear()" class="weui-search-bar__cancel-btn" id="searchCancel">cancel</a>
    </div>

We perform event handling on the JS code, as shown below.

The main purpose is to monitor the content changes of Input control, to make timely queries and content display.

//Query Box Input Trigger Event
$('#searchInput').bind('input propertychange', function () {
    var name = $("#searchInput").val();

    //Obtain Json Collection of objects and generation of data display content
    var url = "/h5/FindDrugWithPager?page=1&rows=5&Name=" + encodeURI(name);
    $.getJSON(url, function (data) {
        $("#searchContent").html("");
        var html = "";
        $.each(data.rows, function (i, item) {
            var background = (i % 2 == 0) ? "background-color:Highlight" : "";
            html += `<li>
               <div class='pic'><img src='@ViewBag.WebsiteDomain/Content/images/drug.png' /></div>
               <div class='text'>
                    <h2><i></i><span>` + item.CommonName + `</span><em>`+ item.Specification +`</em></h2>
                    <p>Commodity name:` + item.ProductName + `</p>
                    <p>Manufactor:`+item.Manufacturer  +`</p>
               </div>
               <a class='ture' href=\"javascript:;\" onclick=\"AddDrug('` + item.ID + `','`+ item.ProductName  +`')\" ><img src='@ViewBag.WebsiteDomain/Content/images/add1-24.png'></a>
            </li>`;
        });
        $("#searchContent").html(html);
    });
});

function cancel() {
    $("#searchContent").empty();
}

function clear() {

    $('#searchInput').val('')
    $("#searchContent").empty();
}

Here's the HTML template, which we sometimes use as a code block to insert variables into the template code, as shown below.

$.getJSON("/Qyh5Flow/GetImageList2?attachGuid=" + info.AttachGUID, function (data) {
    $.each(data, function (i, item) {
        $("#previewImage").append(`<img class="weui-preview-box" src='${item.Text}' id='img_${item.Value}'/>`);
    });
});

The code block here uses the ` ` symbol block for the start and end, which inserts variable strings such as ${item.Text}, ${item.Value} without interrupting the content of the template. If there are multiple lines, it is very convenient for us to do the same.

$.getJSON(url, function (data) {
    var html = "";
    $.each(data.rows, function (i, item) {
        html += `<div class="weui-panel weui-panel_access">
            <div class="weui-panel__hd">
                <span>${item.FormName}</span>: <span>${item.EditorName}</span>,<span>${item.Edittime}</span>
                <span class="ord-status-txt-ts fr"><b>${GetStatus(item.Status)}</b></span>
            </div>
            <div class="weui-media-box__bd  pd-10">
                <div class="weui-media-box_appmsg ord-pro-list">
                    <div class="weui-media-box__bd">
                        <p class="weui-media-box__desc">Title:<span>${item.Title}</span></p>
                        <div class="clear mg-t-10">
                            <div class="pro-amount fl"><span class="font-13">Current processing type:<em class="num font-15">${item.Proc_TypeName}</em></span></div>
                            <div class="pro-amount fr"><span class="font-13">Current Processor:<em class="name">${item.Proc_UserName}</em></span></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="weui-panel__ft">
                <div class="weui-cell weui-cell_access weui-cell_link oder-opt-btnbox">
                    <a href="${item.ViewUrl}?id=${item.ID}" class="ords-btn-dele">View details</a>
                </div>
            </div>
        </div>`;

    });

    $("#" +divname).html(html);
});

This is the JS code block that we recommend to use. The whole block of code does not affect reading, and can be typesetted in a new line, which is very intuitive.(

 

11) Interface popup handling

There are several conventional pop-up window treatments defined in Weui.

Dialog boxes can only be invoked through JavaScript. WeUI on WeChat offers three commonly used dialog boxes, Alert, Confirm, Prompt and Login.We can also customize dialogs through $.modal

In fact, Alert, Confirm, Prompt, and Login are all customizations of Modal.

 

The general JS call code is shown below.

//General Tip Window
$.alert("Customized message content", "Custom Title");

//Confirmation prompt window
$.confirm("Customized message content", "Custom Title", function() {
  //Callback function after clicking confirmation
  }, function() {
  //Click the callback function after canceling
  });

For example, in process form processing, the user is prompted to confirm the processing before the operation.

//Return to drafter for reprocessing
function ApplyCancel(opinion) {
    var tipMessage2 = "Are you sure you want to submit your data once it has been checked and if you confirm that it is correct to return it to the drafter for reprocessing?";
    $.confirm(tipMessage2, "Return to drafter for reprocessing?", function () {
        var userid = "@ViewBag.userid";
        var applyid = "@Request["id"]";
        var url = "/QyH5Flow/SkipFirstApply";
        //Construction parameters sent to the background
        var postData = {
            userid: userid,
            applyId: applyid,
            opinion: opinion
        };
        $.post(url, postData, function (json) {
            var data = $.parseJSON(json);
            if (data.Success) {
                //console.log(data);
                //Prompt for processing results
                $.toast("You have returned to the agent for modification.");

                $.closePopup();
                initControls();//Reload
            }
            else {
                $.toast("operation failed:" + data.ErrorMessage);
            }
        });

    }, function () {
        //Cancel operation
    });
}

The landing window interface effect is shown below.

 

$.login("Customized message content", function(username, password) {
  // Log in here
}, function() {
});

//If there are too many parameters, pass object Mode Incoming
$.login({
  title: 'Title',
  text: 'Copy Writer',
  username: 'tom',  // Default User Name
  password: 'tom',  // Default password
  onOK: function (username, password) {
    //Click to confirm
  },
  onCancel: function () {
    //Click Cancel
  }
});

We can use the login box to bind a system account, as follows is the actual project processing code.

$(document).on('click', '#btnBind', function() {
    $.login({
      title: 'Sign in',
      text: 'Please enter a username and password',
      onOK: function (username, password) {
          var url = "/H5/VerifyUser?openid=@ViewBag.openid";
          var postData = {
              username: username,
              password: password
          };

          $.post(url, postData, function (json) {
              //Escape JSON As an object
              var data = $.parseJSON(json);
              if (data.Success) {
                  $.toptip('Login Successful!');
                  location.reload();//Refresh
                  //WeixinJSBridge.call('closeWindow');//close window
              }
              else {
                  $.toptip("Logon Failure:" + data.ErrorMessage, "forbidden");
              }
          });
      },
      onCancel: function () {
        $.toptip('Cancel Logon!', 'cancel');
      }
    });
});

These dialogs are a special form of $.modal.You can customize the dialog box with $.modal

$.modal({
  title: "Hello",
  text: "I'm customized modal",
  buttons: [
    { text: "Alipay", onClick: function(){ console.log(1)} },
    { text: "WeChat Payment", onClick: function(){ console.log(2)} },
    { text: "cancel", className: "default", onClick: function(){ console.log(3)} },
  ]
});

By default, clicking on a dialog's button will close the dialog before triggering the callback function.You can close any dialog box that is being displayed through JS:

$.closeModal();

 

In addition to the modal dialog boxes for the above scenarios, there is also a Popup pop-up scenario that obscures the page below, such as in the case of a regular shopping cart.

A Popup is an overlay pop-up that completely covers the current page or half of it.

For example, in the process processing page, when I need to review and sign up for processing, the corresponding processing content pops up, which is the use scenario of Popup.

 

We invoke the display window through JS.

$("#SignAction").popup();//Active pop-up window

The SignAction layer is the window layer for a popup, and the view HTML code is shown below.

 

We just need to notice the description of class='weui-popup_u container popup-bottom', to know its style, the Popup window that pops up from the bottom.

If you don't add a Popup-bottom style, it's full-screen coverage.

Close Popup

Add class='close-popup'to any link and click to close the currently open popup. You can also close it with $.closePopup().(

 

12) Integration of WeChat JSSDK and other processing

WeChat JSSDK provides a lot of rich functions, we can use JSSDK to upload pictures, preview, scanner and so on. Since I use the attachment upload method to upload pictures, I do not introduce the more cumbersome JSSDK picture upload mode. I am interested in referring to my previous article " Using WeChat JSSDK and using URL.createObjectURL to upload preview pictures Understand the difference.

a) Picture Preview

Usually, in some view interfaces for viewing content, we often preview pictures. At this time, we can use JSSDK's picture preview interface. Before using JSSDK interface, we need to initialize the interface before we can call it. Below is the case code for initialization and invocation.

    <!--WeChat API Initialization-->
    <script language="javascript">
        var appid = '@ViewBag.appid';
        var noncestr = '@ViewBag.noncestr';
        var signature = '@ViewBag.signature';
        var timestamp = '@ViewBag.timestamp';

        wx.config({
            debug: false,
            appId: appid, // Required, unique identification of public number
            timestamp: timestamp, // Required, time stamp for signature generation
            nonceStr: noncestr, // Required, generate a random string of signatures
            signature: signature, // Required, signed, see Appendix 1
            jsApiList: [
                'checkJsApi',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'
            ]
        });

        //When all is ready, add the corresponding collection through style lookup and bind click Event
        wx.ready(function () {
            var $images = $(".preview").find("img");
            var imgPaths = [];
            $images.each(function(){
                imgPaths.push(this.src);
            });

            $images.on("click",function(){
                wx.previewImage({
                    current: this.src,
                    urls: imgPaths
                });
            });
        });
    </script>

Initialization of pictures can be done in HTML code.

<div id="previewImage" class="preview">
    @if (ViewBag.PresImages != null)
    {
        for (var i = 0; i < ViewBag.PresImages.Count; i++)
        {
            <img class="weui-preview-box" src='@ViewBag.PresImages[i]' alt="Prescription picture">
        }
    }
</div>

b) Call sweep processing

We can use JSSDK to call the mobile phone's scanner operation and let it do the corresponding scanner processing, as follows is the JS code that uses JSSDK to scanner.

    <script language="javascript">
        var appid = '@ViewBag.appid';
        var noncestr = '@ViewBag.noncestr';
        var signature = '@ViewBag.signature';
        var timestamp = '@ViewBag.timestamp';

        wx.config({
            debug: false,
            appId: appid, // Required, unique identification of public number
            timestamp: timestamp, // Required, time stamp for signature generation
            nonceStr: noncestr, // Required, generate a random string of signatures
            signature: signature, // Required, signed, see Appendix 1
            jsApiList: [
                'checkJsApi',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'scanQRCode'
            ]
        });

        //When all is ready
        wx.ready(function () {
            document.querySelector('#scancode').onclick = function () {//Call sweep event to return sweep value
                wx.scanQRCode({
                    needResult: 1,
                    desc: 'scanQRCode desc',
                    success: function (res) {
                        //console.log(res.resultStr);
                        var isUrl = CheckUrl(res.resultStr);
                        if (isUrl) {
                            location.href = res.resultStr;//Jump Page
                        }
                    }
                });
            };
        });
        //Verification URL Character string
        function CheckUrl(str) {
            var RegUrl = new RegExp();
            RegUrl.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");//jihua.cnblogs.com
            if (!RegUrl.test(str)) {
                return false;
            }
            return true;
        }
    </script>

After sweeping above, identify the judgement URL, if it is a URL, then the page address is automatically adjusted to the corresponding interface.

These are all kinds of interface processing and JS processing codes used in some practical projects. I hope you can give more support and encouragement.

Tags: ASP.NET JSON JQuery QRCode Javascript

Posted on Wed, 25 Mar 2020 02:08:30 -0400 by phpprogrammer