form and template engine for front-end and back-end interaction

Posted by sgs-techie on Sat, 01 Jan 2022 14:03:47 +0100

catalogue

1, Form form

1.1 label properties

1.1.1 action

1.1.2 target

1.1.3 method

1.1.4 enctype

1.2} form synchronous submission and shortcomings

1.3} submit form data through Ajax

1.3. 1. Listen for form submission events

1.3. 2. Block the default behavior of the form

1.4. serialize() method

Two. Template engine

2.1} art template usage steps

2.2} art template standard syntax

2.3} regular and string operations

1, Form form

It is mainly responsible for the data collection function in the web page. It is composed of form label, form field and form button.

1.1 label properties

It is used to specify how to send the collected data to the server.

1.1.1 action

The action attribute value should be a URL provided by the backend.

  • When the < form > form does not specify the action attribute value, the default value of action is the URL address of the current page.
  • When the form is submitted, the page will immediately jump to the URL address specified by the action attribute.

1.1.2 target

1.1.3 method

Specify how to submit the form data to the action URL.

  • get: it is suitable for submitting a small amount of simple data. The data will be displayed in the url address
  • post: it is suitable for submitting a large number of complex or file upload data. The data will not be displayed in the url address, which has high security

1.1.4 enctype

Specifies how to encode form data before sending it.  

1.2} form synchronous submission and shortcomings

Synchronous submission of forms: click the submut button to trigger the form submission operation, so as to make the page Jump to the aciton URL.

Disadvantages: the whole page will jump to the address pointed to by the action URL, resulting in poor user experience. The status and data before the page will be lost.

Solution: the form is only responsible for collecting data, and Ajax is responsible for submitting the data to the server.

1.3} submit form data through Ajax

1.3. 1. Listen for form submission events

$('form name') submit(function (e) {};

$('form name') on('submit', function(e) {};

1.3. 2. Block the default behavior of the form

e.preventDefault();

1.4. serialize() method

Format: $(selector) serialize();

Quickly obtain form data; You must add a name attribute for each form element

Case display

design sketch:

 

Code display: (html+js)

<!-- Comments panel -->
<div class="panel panel-primary">
     <div class="panel-heading">
          <h3 class="panel-title">Comment</h3>
     </div>
     <form class="panel-body" id="formAddCmt">
          <div>Commented by:</div>
          <input type="text" class="form-control" name="username" autocomplete="off" />
          <div>Comments:</div>
          <textarea class="form-control" name="content"></textarea>
          <button type="submit" class="btn btn-primary">Comment</button>
     </form>
</div>

<!-- Comment list -->
<ul class="list-group" id="cmt-list">
    <li class="list-group-item">
        <span class="badge" style="background-color: #F0AD4E; "> comment time:</span>
        <span class="badge" style="background-color: #5BC0DE; "> commented by: < / span > item 1
    </li>
</ul>
function getCommentList() {
    $.ajax({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/cmtlist',
        data: {},
        success: function(res) {
            if (res.status !== 200) return alert('Failed to get comment list!');
            // console.log('data acquisition succeeded ');

            var rows = [];
            $.each(res.data, function(i, item) { //Circular splice string
                var str = '<li class="list-group-item"><span class="badge" style="background-color: #F0AD4E;">Comment time:' + item.time + '</span><span class="badge" style="background-color: #5BC0DE; "> commented by: '+ item. Username +' < / span > '+ item. Content +' < / Li > ';
                rows.push(str);
            })
            $('#cmt-list').empty().append(rows.join(''))
        }
    });
};
getCommentList();

$(function() {
    $("#formAddCmt").submit(function(e) {
        e.preventDefault();
        var data = $(this).serialize();
        console.log(data);
        $.post('http://www.liulongbin.top:3006/api/addcmt', data, function(res) {
            if (res.status !== 201) {
                return alert('Failed to comment!')
            }
            getCommentList();
            $('#formAddCmt')[0].reset();
        });
    });

});

Two. Template engine

Automatically generate a complete HTML page according to the template structure and data specified by the programmer.

It reduces string splicing, makes the structure code clearer, and makes the code easier to read and maintain.

2.1} art template usage steps

  1. Import template engine: template web js
  2. Render function (define data)
  3. The html of the template must be defined to script (define template)
  4. Call the template function
  5. Render HTML structure

2.2} art template standard syntax

Standard syntax: variable output or circular array can be performed in {}}
Original output
    {{@  value}}
Conditional output
{{if v1}} output content {{else if v2}} output content {{/ if}}
{{if value}} output content {{/ if}}
Cyclic output
    {{each arr}}     {{$index}},{{$value}}      {{/each}}

2.3} regular and string operations

exec() function
Used to retrieve a match for a regular expression in a string
If there is a matching value, null will be returned if the matching fails
Extract group
The content wrapped in () in regular expression represents a group, and you can extract the content you want by grouping
replace() function
Replace operation str.replace of string (replaced element, replaced element]);

Comprehensive case

design sketch:

Import related files

Code display: (html+js)

 <div class="container">
        <!-- Logo -->
        <img src="./images/taobao_logo.png" alt="" class="logo" />

        <div class="box">
            <!-- tab column -->
            <div class="tabs">
                <div class="tab-active">baby</div>
                <div>shop</div>
            </div>
            <!-- Search area (search box and search button) -->
            <div class="search-box">
                <input id="ipt" type="text" class="ipt" placeholder="Please enter the content to search" /><button class="btnSearch">
          search
        </button>
            </div>
            <!-- Search suggestion list -->
            <div id="suggest-list"></div>
        </div>
  </div>
 <script type="text/html" id="tpl-suggestList">
        {{each result}}
        <!-- Search suggestions -->
        <div class="suggest-item">{{$value[0]}}</div>
        {{/each}}
 </script>
<script>
        $(function() {
            //1. Define the delayer ID
            var timer = null;
            //(1) Define global cache objects
            var cacheobj = {}

            //2. Define the anti shake function
            function debounceSearch(kw) {
                timer = setTimeout(function() {
                    getSuggestList(kw);
                }, 800)
            }


            //Bind keyup event for input box
            $('#ipt').on('keyup', function() {
                //3. Clear the time delay
                clearTimeout(timer);
                //trim remove spaces
                var keywords = $(this).val().trim();
                if (keywords.length <= 0) {
                    return $('#suggest-list').empty().hide();
                }
                //First determine whether there is data in the cache 
                if (cacheobj[keywords]) {
                    return renderSuggestList(cacheobj[keywords]);
                }
                //Call after input
                debounceSearch(keywords);
            });

            function getSuggestList(kw) {
                $.ajax({
                    url: 'https://suggest.taobao.com/sug?q=' + kw,
                    dataType: 'jsonp',
                    success: function(res) {
                        renderSuggestList(res);
                    }
                })
            };

            //Rendering suggestion list
            function renderSuggestList(res) {
                if (res.result.length <= 0) {
                    return $('#suggest-list').empty().hide();
                }
                var htmlStr = template('tpl-suggestList', res);
                $('#suggest-list').html(htmlStr).show();

                //(2) Save search results to cached objects
                //Get user input as a key
                var k = $('#ipt').val().trim();
                //You need to cache the data as a value
                cacheobj[k] = res;
            }

        })
</script>

Topics: html server