Ajax programming --- the use of client-side template engine

1. Template engine

In a traditional website, the client sends a request to the server, the server splices the data and html, and then sends the spliced ​​html string to the client.

However, now we use ajax technology to send requests to the server side, and the server side will use json format data as the response content in most cases.

That is to say, the splicing of the original data and html is done on the server side, but now this work needs to be done on the client side .

When performing data splicing on the client side, we also need to use a template engine.

Next, let's explain the client -side template engine

1.1 Overview of Template Engine

Whether it is a client-side template engine or a server-side template engine, its function is: **Use the template syntax provided by the template engine to splicing data and HTML.

In the Node course phase, the art-template template engine (server side) is explained. Moreover, the art-template template engine also has a corresponding client version.

Therefore, on the client side, we can use art-template directly without learning a new template engine. There are only minor changes in usage.

Official address:
https://aui.github.io/art-template/zh-cn/index.html

1.2 Usage steps

  1. Download the art-template template engine file and import the library file in the HTML page
    insert image description here
  2. Prepare the art-template template

Client-side JavaScript does not have the ability to read files, so the client-side template is not a separate file (when learning node before, the template was stored in views/common/layout.art), but a code snippet in an html file, and use script tag and get one for the client-side template id值.
insert image description here

  1. Tell the template engine which template to concatenate with which data

insert image description here

  1. Add the concatenated html string to the page

insert image description here
5. Tell the template engine how to splicing data and html strings through template syntax

insert image description here

2. Code demo

2.1 Example 1: Verifying the uniqueness of the email address

insert image description here

// 验证邮箱地址的正则表达式
var reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/

The specific code is as follows:

js/ajax.jsThe complete code is as follows:

function ajax (options) {
	// 默认值
	var defaults = {
		type: 'get',
		url: '',
		async: true,
		data: {},
		header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		success: function () {},
		error: function () {}
	}
	// 使用用户传递的参数替换默认值参数
	Object.assign(defaults, options);
	// 创建ajax对象
	var xhr = new XMLHttpRequest();
	// 参数拼接变量
	var params = '';
	// 循环参数
	for (var attr in defaults.data) {
		// 参数拼接
		params += attr + '=' + defaults.data[attr] + '&';
		// 去掉参数中最后一个&
		params = params.substr(0, params.length-1)
	}
	// 如果请求方式为get
	if (defaults.type == 'get') {
		// 将参数拼接在url地址的后面
		defaults.url += '?' + params;
	}

	// 配置ajax请求
	xhr.open(defaults.type, defaults.url, defaults.async);
	// 如果请求方式为post
	if (defaults.type == 'post') {
		// 设置请求头
		xhr.setRequestHeader('Content-Type', defaults.header['Content-Type']);
		// 如果想服务器端传递的参数类型为json
		if (defaults.header['Content-Type'] == 'application/json') {
			// 将json对象转换为json字符串
			xhr.send(JSON.stringify(defaults.data))
		}else {
			// 发送请求
			xhr.send(params);
		}
	} else {
		xhr.send();
	}
	// 请求加载完成
	xhr.onload = function () {
		// 获取服务器端返回数据的类型
		var contentType = xhr.getResponseHeader('content-type');
		// 获取服务器端返回的响应数据
		var responseText = xhr.responseText;
		// 如果服务器端返回的数据是json数据类型
		if (contentType.includes('application/json')) {
			// 将json字符串转换为json对象
			responseText = JSON.parse(responseText);
		}
		// 如果请求成功
		if (xhr.status == 200) {
			// 调用成功回调函数, 并且将服务器端返回的结果传递给成功回调函数
			defaults.success(responseText, xhr);
		} else {
			// 调用失败回调函数并且将xhr对象传递给回调函数
			defaults.error(responseText, xhr);
		} 
	}
	// 当网络中断时
	xhr.onerror = function () {
		// 调用失败回调函数并且将xhr对象传递给回调函数
		defaults.error(xhr);
	}
}

02-验证邮箱地址唯一性.htmlFull code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
    <style type="text/css">
        p:not(:empty) {
     
     
            padding: 15px;
        }
        
        .container {
     
     
            padding-top: 100px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="form-group">
            <label>邮箱地址</label>
            <input type="email" class="form-control" placeholder="请输入邮箱地址" id="email">
        </div>
        <!-- 错误 bg-danger 正确 bg-success -->
        <p id="info"></p>
    </div>
    <script src="/js/ajax.js"></script>
    <script>
        // 获取页面中的元素
        var emailInp = document.getElementById('email')
        var info = document.getElementById('info')

        // 给emailInp添加离开焦点事件
        emailInp.onblur = function() {
     
     
            // 获取用户输入的邮箱地址
            var email = this.value
                // 验证邮箱地址的正则表达式
            var reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
                // 如果用户输入的邮箱地址不符合规则
            if (!reg.test(email)) {
     
     
                // 阻止程序向下执行
                info.innerHTML = '请输入符合规则的邮箱地址'
                info.className = 'bg-danger'
                return;
            }

            // 向服务器端发送请求
            ajax({
     
     
                type: 'get',
                url: 'http://localhost:3000/verifyEmailAdress',
                data: {
     
     
                    email: email
                },
                success: function(result) {
     
     
                    console.log(result)
                    info.innerHTML = result.message;
                    info.className = 'bg-success';
                },
                error: function(result) {
     
     
                    console.log(result)
                    info.innerHTML = result.message;
                    info.className = 'bg-danger';
                }
            })
        }
    </script>
</body>

</html>

app.jsThe corresponding code in:

// 邮箱地址验证
app.get('/verifyEmailAdress', (req, res) => {
    // 接收客户端传递过来的邮箱地址
    const email = req.query.email;
    // 判断邮箱地址注册过的情况
    if (email == '[email protected]') {
        // 设置http状态码并对客户端做出响应
        res.status(400).send({ message: '邮箱地址已经注册过了, 请更换其他邮箱地址' });
    } else {
        // 邮箱地址可用的情况
        // 对客户端做出响应
        res.send({ message: '恭喜, 邮箱地址可用' });
    }
});

2.2 Example 2: Automatically prompt the content of the search box

insert image description hereinsert image description here

The specific code is as follows:

03-搜索框内容自动提示.htmlThe complete code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
    <style type="text/css">
        .container {
     
     
            padding-top: 150px;
        }
        
        .list-group {
     
     
            display: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="请输入搜索关键字" id="search">
            <ul class="list-group" id="list-box">

            </ul>
        </div>
    </div>
    <script src="/js/ajax.js"></script>
    <script src="/js/template-web.js"></script>
    <script type="text/html" id="tpl">
        {
     
     {
     
     each result}}
        <li class="list-group-item">{
     
     {
     
     $value}}</li>
        {
     
     {
     
     /each}}
    </script>
    <script>
        // 获取搜索框
        var searchInp = document.getElementById('search')
            // 获取提示文字的存放容器
        var listBox = document.getElementById('list-box')
            // 存储定时器的变量
        var timer = null
            // 当用户在文本框中输入的时候触发
        searchInp.oninput = function() {
     
     
            // 清除上一次开启的定时器
            clearTimeout(timer)
                // 获取用户输入的内容
            var key = this.value


            if (key.trim().length == 0) {
     
     
                // 如果用户没有在搜索框中输入内容
                // 将提示下拉框隐藏掉
                listBox.style.display = 'none'
                    // 组织程序向下执行
                return;
            }
            // 开启定时器,让请求延时发送
            timer = setTimeout(function() {
     
     

                // 向服务器端发送请求
                // 向服务器端索取和用户输入关键字相关的内容
                ajax({
     
     
                    type: 'get',
                    url: 'http://localhost:3000/searchAutoPrompt',
                    data: {
     
     
                        key: key
                    },
                    success: function(result) {
     
     
                        // 使用模板引擎拼接字符串
                        var html = template('tpl', {
     
     
                                result: result
                            })
                            // 将拼接好的字符串显示在页面中
                        listBox.innerHTML = html
                            // 显示ul容器
                        listBox.style.display = 'block'
                    }
                })
            }, 800)
        }
    </script>
</body>

</html>

The corresponding code in app.js:

// 输入框文字提示
app.get('/searchAutoPrompt', (req, res) => {
    // 搜索关键字
    const key = req.query.key;
    // 提示文字列表
    const list = [
        '黑马程序员',
        '黑马程序员官网',
        '黑马程序员顺义校区',
        '黑马程序员学院报名系统',
        '传智播客',
        '传智博客前端与移动端开发',
        '传智播客大数据',
        '传智播客python',
        '传智播客java',
        '传智播客c++',
        '传智播客怎么样'
    ];
    // 搜索结果
    let result = list.filter(item => item.includes(key));
    // 将查询结果返回给客户端
    res.send(result);
});

Guess you like

Origin blog.csdn.net/weixin_47505105/article/details/123389336