Ajax Complete steps to get node server data

  • 2021-08-28 07:11:48
  • OfStack

Step 1 Prepare

Because it is necessary to put the data obtained by the server in the web page, it is necessary to render the page. Here I prepare the art-template template

2. Prepare the server

The server should prepare the data to be rendered to the page

3. Page action

What I do here is a search box prompt function explanation is all in the code comment

The server code is as follows


//  Text prompt for input box 
app.get("/searchAutoPrompt", (req, res) => {
 //  Search keywords 
 const key = req.query.key;
 //  Prompt text list 
 const list = [" Baidu ", " Baidu official website ", " Baidu game ", " Baidu network disk "];
 //  Search results  filter Yes 1 A traversed function  includes ( key ) is a string that contains key All return 
 let result = list.filter((item) => item.includes(key));
 //  Return the query results to the client 
 res.send(result);
});

Page code:

I used a encapsulated Ajax function for the following code

The 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] + '&';
  // 去掉参数中最后1个&
  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);
 }
}


<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 () {
  // 清除上1次开启的定时器
  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>

Summarize


Related articles: