Ajax+Git study notes

Ajax+Git study notes

Ajax

basic concept

Server : in the process of surfing the Internet, responsible forStore and provide resources externallyComputer

Client : in the process of surfing the Internet, responsible forAcquiring and consuming resourcesComputer

URL address : Uniform resource locator, used to identify the unique storage location of each resource on the Internet. Only through the URL address, the browser can correctly locate the storage location of the resource, so as to successfully access the corresponding resource

The URL address generally consists of three parts:
① The communication protocol between the client and the server
② The name of the server where the resource is stored
③ The specific storage location of the resource on the server

insert image description here
Communication process between client and server : request – processing – response

Web page request data : If you want to request data resources on the server in the web page, you need to use the XMLHttpRequest object用法 var xhrObj = new XMLHttpRequest()

Resource request method : for get and post requests

Ajax : In the way of data interaction between the XMLHttpRequest object and the server in the web page, Ajax allows us to easily realize the data interaction between the web page and the server

Ajax in jQuery

The three most commonly used methods for initiating Ajax requests in jQuery are:
$.get(),$.post() ,$.ajax()

  1. Syntax of the $.get() function
 $.get(url, [data], [callback])
//发起不带参数的请求
 $.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
    
    
    console.log(res) // 这里的 res 是服务器返回的数据
})
//发起带参数的请求
$.get('http://www.liulongbin.top:3006/api/getbooks', {
    
     id: 1 }, function(res) {
    
    
    console.log(res)
})

insert image description here
2. Syntax of $.post() function

//向服务器提交数据
$.post(url, [data], [callback])
  1. Syntax of the $.ajax() function
$.ajax({
    
    
   type: '', // 请求的方式,例如 GET 或 POST
   url: '',  // 请求的 URL 地址
   data: {
    
     },// 这次请求要携带的数据
   success: function(res) {
    
     } // 请求成功之后的回调函数
})

interface

When using Ajax to request data, the requested URL address is called the data interface (interface for short). At the same time, each interface must have a request method

Interface testing tool Postman : In order to verify whether the interface can be accessed normally, we often need to use the interface testing tool to detect the data interface. The interface testing tool allows us to call and test the interface without writing any code.

Components of the interface document : Contains the following 6 items to provide a basis for calling the interface:

  • Interface name: a simple description used to identify each interface, such as the login interface, the interface for obtaining the book list, etc.
  • Interface URL: the calling address of the interface.
  • Calling method: the calling method of the interface, such as GET or POST.
  • Parameter format: the parameters that need to be passed by the interface, each parameter must contain four items: parameter name, parameter type, whether it is required, and parameter description.
  • Response format: a detailed description of the return value of the interface, generally including data name, data type, and description.
  • Return example (optional): In the form of an object, enumerate the structure of the data returned by the server.

form

The form is mainly responsible for the data collection function in the web page.
The form is composed of three basic parts:

  • form label<form></form>

  • form field
    <input type="text" name="email_or_mobile" />
    <input type="password" name="password" />
    <input type="checkbox" name="remember_me" checked />

  • form button<button type="submit">提交</button>
    insert image description here

properties of the label

  1. action: Used to specify where to send the form data when the form is submitted.
    The value of the action attribute should be a URL address provided by the backend, which is specially responsible for receiving the data submitted by the form.

  2. target: It is used to specify where to open the action URL.
    There are 5 optional values. By default, the value of target is _self, which means to open the action URL in the same frame
    insert image description here

  3. method: It is used to specify how to submit the form data to the action URL.
    There are two optional values, namely get and post.
    By default, the value of method is get, which means that the form data is submitted to the action URL in the form of URL address
    get 方式适合用来提交少量的、简单的数据。
    post 方式适合用来提交大量的、复杂的、或包含文件上传的数据。
    在实际开发中,post 提交方式用的最多

  4. enctype: specifies how to encode the data before sending the form data.
    There are three optional values:
    insert image description here

Notice:

  • When it comes to file upload operations, the value of enctype must be set to multipart/form-data
  • If the submission of the form does not involve the file upload operation, just set the value of enctype to application/x-www-form-urlencoded directly!

Synchronous submission of forms

Definition : By clicking the submit button, the action of triggering the form submission, so that the page jumps to the action URL, is called the synchronous submission of the form.
Disadvantages :

  1. After the form is submitted synchronously, the entire page will jump to the address pointed to by the action URL, and the user experience is very poor.
  2. After the form is submitted synchronously, the previous state and data of the page will be lost.

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

Submit form data via Ajax

  1. Listen for form submit events
<body>
  <form action="/login" id="f1">
    <input type="text" name="user_name" />
    <input type="password" name="password" />
    <button type="submit">提交</button>
  </form>

  <script>
    $(function () {
      
      
      // 第一种方式
      // $('#f1').submit(function () {
      
      
      //   alert('监听到了表单的提交事件')
      // })

      // 第二种方式
      $('#f1').on('submit', function () {
      
        
        alert('监听到了表单的提交事件2')
      })
    })
  </script>
</body>
  1. Prevent form default submit behavior
<body>
  <form action="/login" id="f1">
    <input type="text" name="user_name" />
    <input type="password" name="password" />
    <button type="submit">提交</button>
  </form>
  <script>
    $(function () {
      
      
      // 第一种方式
      // $('#f1').submit(function (e) {
      
      
      //   alert('监听到了表单的提交事件')
      //   e.preventDefault()
      // })
      // 第二种方式
      $('#f1').on('submit', function (e) {
      
        
        alert('监听到了表单的提交事件2')
        e.preventDefault()
      })
    })
  </script>
</body>
  1. Quickly get the data in the form: $(selector).serialize(), you can get all the data in the form at one time
<body>

  <form action="/login" id="f1">
    <input type="text" name="user_name" />
    <input type="password" name="password" />
    <button type="submit">提交</button>
  </form>

  <script>
    $(function () {
      
      
      // 第一种方式
      /* $('#f1').submit(function (e) {
        e.preventDefault()
        var data = $(this).serialize()
        console.log(data)
      }) */

      // 第二种方式
      $('#f1').on('submit', function (e) {
      
      
        e.preventDefault()
        var data = $('#f1').serialize()
        console.log(data)
      })
    })
  </script>
</body>

template engine

Can automatically generate a complete HTML page according to the template structure and data specified by the programmer

Advantages :

  1. Reduced string concatenation operations
  2. Make the code structure clearer
  3. Make code easier to read and maintain

art-template template engine

Minimalistic, ultra-fast templating engine.
The home page of the Chinese official website is http://aui.github.io/art-template/zh-cn/index.html
Download link: http://aui.github.io/art-template/zh-cn/docs/installation.html
traditional UI structure rendering problem: complex structure, troublesome modification

Steps to use art-template

  1. import art-template
  2. define data
  3. define template
  4. call template function
  5. render HTML structure

art-template standard syntax

art-template provides { { }} syntax format, within { { }} you can perform variable output, or loop array and other operations, this { { }} syntax is called standard syntax in art-template.
In the { { }} syntax, variable output, object attribute output, ternary expression output, logical or output, addition, subtraction, multiplication, and division can be output.

Original text output :
{ {@ value }}
If the value to be output contains the HTML tag structure, you need to use the original text output syntax to ensure that the HTML tags are rendered normally

Conditional output :
it can be used in { { }} if … else if … /iffor on-demand output

<div>
      {
   
   {if flag === 0}}
      flag的值是0
      {
   
   {else if flag === 1}}
      flag的值是1
      {
   
   {/if}}
</div>

Loop output :
If you want to implement loop output, you can use the each syntax to loop the array within { { }}, the index of the current loop is accessed using $index, and the current loop item is accessed using $value

<div>
      {
   
   {each arr}}
      {
   
   {$index}} {
   
   {$value}}
      {
   
   {/each}}
</div>
<ul>
      {
   
   {each hobby}}
      <li>索引是:{
   
   {$index}},循环项是:{
   
   {$value}}</li>
      {
   
   {/each}}
    </ul>

Standard Syntax - Filters

The essence of a filter is a function processing function.
{ {value | filterName}}
The filter syntax is similar to the pipeline operator, and its previous output is used as the next input.
The basic syntax for defining a filter:template.defaults.imports.filterName = function(value){/*return处理的结果*/}

<body>
  <script type="text/html" id="tpl-user">
    <h3>{
      
      {
      
      regTime | dateFormat}}</h3>
  </script>

  <script>
    // 定义处理时间的过滤器
    template.defaults.imports.dateFormat = function (date) {
      
      
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()

      return y + '-' + m + '-' + d
    }
  </script>
</body>

Implementation principle of template engine

Regular and string operations
The exec() function is used to retrieve the match of the regular expression in the string
If there is a matching value in the string, it returns the matching value, otherwise it returns null
RegExpObject.exec(string)

var str = 'hello'
var pattern = /o/
// 输出的结果["o", index: 4, input: "hello", groups: undefined]
console.log(pattern.exec(str)) 

Grouping :
The content wrapped in () in the regular expression represents a grouping, and you can extract the content you want by grouping

The replace function
is used to replace some characters with other characters in a string
var result = '123456'.replace('123', 'abc') // 得到的 result 的值为字符串 'abc456'

Implement a simple template engine

Implementation steps:

  1. Define template structure
<!-- 1.定义模板结构 -->
<script type="text/html" id="tpl-user">
   <div>姓名:{
      
      {
      
      name}}</div>
   <div>年龄:{
      
      {
      
       age }}</div>
   <div>性别:{
      
      {
      
        gender}}</div>
   <div>住址:{
      
      {
      
      address  }}</div>
</script>
  1. pre-call template engine
<script>
   // 定义数据
   var data = {
      
       name: 'zs', age: 28, gender: '男', address: '北京顺义马坡' }
   // 调用模板函数
   var htmlStr = template('tpl-user', data)
   // 渲染HTML结构
   document.getElementById('user-box').innerHTML = htmlStr
</script>
  1. Encapsulate template function
function template(id, data) {
    
    
  var str = document.getElementById(id).innerHTML
  var pattern = /{
     
     {\s*([a-zA-Z]+)\s*}}/
  var pattResult = null
  while ((pattResult = pattern.exec(str))) {
    
    
    str = str.replace(pattResult[0], data[pattResult[1]])
  }
  return str
}
  1. Import and use a custom template engine
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>自定义模板引擎</title>
    <!-- 导入自定义的模板引擎 -->
    <script src="./js/template.js"></script>
</head>

XMLHttpRequest

XMLHttpRequest (xhr for short) is a Javascript object provided by the browser, through which data resources on the server can be requested. The Ajax function in jQuery learned before is encapsulated based on the xhr object

Use xhr to initiate a GET request

  1. create xhr object
  2. Call the xhr.open() function
  3. Call the xhr.send() function
  4. Listen to the xhr.onreadystatechange event
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,指定 请求方式 与 URL地址
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
// 3. 调用 send 函数,发起 Ajax 请求
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
    
    
// 4.1 监听 xhr 对象的请求状态 readyState ;与服务器响应的状态 status
    if (xhr.readyState === 4 && xhr.status === 200) {
    
    
        // 4.2 打印服务器响应回来的数据
        console.log(xhr.responseText)
    }
}

The readyState attribute of the XMLHttpRequest object is used to indicate the state of the current Ajax request.
insert image description here

Use xhr to initiate a GET request with parameters

When using the xhr object to initiate a GET request with parameters, you only need to specify the parameters for the URL address during the call to xhr.open

xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
Query strings (URL parameters) are strings (variables) that are appended to the end of the URL to send information to the server

Put the English ? at the end of the URL, and then add the parameter = value. If you want to add multiple parameters, use the & symbol to separate them. In this form, you can add data you want to send to the server to the URL.
// 不带参数的 URL 地址
http://www.liulongbin.top:3006/api/getbooks
// 带一个参数的 URL 地址
http://www.liulongbin.top:3006/api/getbooks?id=1
// 带两个参数的 URL 地址
http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记

URL encoding

Encode Chinese characters and use English characters to represent non-English characters.
The browser provides URL encoding and decoding APIs, which are:
encodeURI() encoding function
decodeURI() and decoding function

Use xhr to initiate a POST request

// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
// 3. 设置 Content-Type 属性(固定写法)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send(),同时将数据以查询字符串的形式,提交给服务器
xhr.send('bookname=水浒传&author=施耐庵&publisher=天津图书出版社')
// 5. 监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === 4 && xhr.status === 200) {
    
    
        console.log(xhr.responseText)
    }
}

data exchange format

The data exchange format is the format for data transmission and exchange between the server and the client. In the front-end field, the two data exchange formats that are often mentioned are XML and JSON.

XML: Extensible Markup Language, less used

Although both XML and HTML are markup languages, there is no relationship between them.

  • HTML is designed toDescribe the content on the page, is the carrier of web content
  • XML is designed toTransfer and store data, is the data carrier

Disadvantages : the XML format is bloated, there are many codes that have nothing to do with the data, the volume is large, and the transmission efficiency is low

JSON: Storing and transferring data between computers and the web

JSON is the string representation of Javascript objects and arrays. It uses text to represent the information of a JS object or array. Therefore, the essence of JSON is a string.
JSON is a lightweight text data exchange format that is smaller than XML. faster and easier to parse

The JSON containsObjects and ArraysTwo structures, through the mutual nesting of these two structures, various complex data structures can be represented

Two structures of JSON

Object structure and array structure

Object structure : The object structure is expressed as the content enclosed by {} in JSON

The key must be a string wrapped in English double quotes, and the data type of value can be number, string, Boolean, null, array, object 6 types

Data structure : key-value pair structure of {key:value, kay:value, …}

The data structure is [ "java", "javascript", 30, true ... ] . The type of data in the array can be number, string, Boolean, null, array, object 6 types

Notes on JSON syntax :

  1. Attribute names must be wrapped in double quotes
  2. Values ​​of type string must be wrapped in double quotes
  3. Single quotes for strings are not allowed in JSON
  4. Comments cannot be written in JSON
  5. The outermost layer of JSON must be in object or array format
  6. Cannot use undefined or functions as JSON values

The relationship between JSON and JS objects :

JSON is a string representation of JS objects, which uses text to represent the information of a JS object, essentially a string

Convert between JSON and JS objects :

// 从 JSON 字符串转换为 JS 对象,使用 JSON.parse() 方法
var obj = JSON.parse('{"a": "Hello", "b": "World"}')
//结果是 {a: 'Hello', b: 'World'}
// 从 JS 对象转换为 JSON 字符串,使用 JSON.stringify() 方法
var json = JSON.stringify({
    
    a: 'Hello', b: 'World'})
//结果是 '{"a": "Hello", "b": "World"}'

Serialization and deserialization :

The process of converting data objects into strings is called serialization. For example, the operation of calling the JSON.stringify() function is called JSON serialization.

The process of converting a string into a data object is called deserialization, for example, the operation of calling the JSON.parse() function is called JSON deserialization.

Encapsulate your own Ajax function

<!-- 1. 导入自定义的ajax函数库 -->
<script src="./itheima.js"></script>
<script>
    // 2. 调用自定义的 itheima 函数,发起 Ajax 数据请求
    itheima({
      
      
        method: '请求类型',
        url: '请求地址',
        data: {
      
       /* 请求参数对象 */ },
        success: function(res) {
      
       // 成功的回调函数
            console.log(res)     // 打印数据
        }
    })
</script>

Define the options parameter option :
itheima() the function is our custom Ajax function, which receives a configuration object as a parameter, and the following properties can be configured in the configuration object:

  • methodtype of request
  • urlRequested URL address
  • dataThe data carried by the request
  • successCallback function after successful request

Handle the data parameter

/**
 * 处理 data 参数
 * @param {data} 需要发送到服务器的数据
 * @returns {string} 返回拼接好的查询字符串 name=zs&age=10
 */
function resolveData(data) {
    
    
  var arr = []
  for (var k in data) {
    
    
    arr.push(k + '=' + data[k])
  }
  return arr.join('&')
}

Define the itheima function
In the itheima() function, you need to create an xhr object and listen to the onreadystatechange event

function itheima(options) {
    
    
  var xhr = new XMLHttpRequest()
  // 拼接查询字符串
  var qs = resolveData(options.data)

  // 监听请求状态改变的事件
  xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === 4 && xhr.status === 200) {
    
    
      var result = JSON.parse(xhr.responseText)
      options.success(result)
    }
  }
}

Judging the type of request
Different request types correspond to different operations of the xhr object, so it is necessary to judge the request type by if ... else ...

  if (options.method.toUpperCase() === 'GET') {
    
    
    // 发起 GET 请求
    xhr.open(options.method, options.url + '?' + qs)
    xhr.send()
  } else if (options.method.toUpperCase() === 'POST') {
    
    
    // 发起 POST 请求
    xhr.open(options.method, options.url)
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    xhr.send(qs)
  }

New features of XMLHttpRequest Level2

Old Cons: 无法读取和上传文件; 没有进度信息
New Features: 可以设置 HTTP 请求的时限, 可以使用 FormData 对象管理表单数据, 可以上传文件,可以获得数据传输的进度信息

Set the HTTP request time limit: timeout attribute

xhr.timeout = 3000
xhr.ontimeout = function(event){
    
    
     alert('请求超时!')
 }

FormData object manages form data

Ajax operations are often used to submit form data. In order to facilitate form processing, HTML5 adds a FormData object, which can simulate form operations

    // 1. 创建 FormData 实例
    var fd = new FormData()
    // 2. 调用 append 函数,向 fd 中追加数据
    fd.append('uname', 'zs')
    fd.append('upwd', '123456')

    var xhr = new XMLHttpRequest()
    xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
    xhr.send(fd)

    xhr.onreadystatechange = function () {
    
    
      if (xhr.readyState === 4 && xhr.status === 200) {
    
    
        console.log(JSON.parse(xhr.responseText))
      }
    }

The FormData object can also be used to get the value of a web form

// 获取表单元素
 var form = document.querySelector('#form1')
 // 监听表单元素的 submit 事件
 form.addEventListener('submit', function(e) {
    
    
    e.preventDefault()
     // 根据 form 表单创建 FormData 对象,会自动将表单数据填充到 FormData 对象中
     var fd = new FormData(form)
     var xhr = new XMLHttpRequest()
     xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
     xhr.send(fd)
     xhr.onreadystatechange = function() {
    
    }
})

Upload files :

Implementation steps :

  1. Define the UI structure
	<!-- 1. 文件选择框 -->
    <input type="file" id="file1" />
    <!-- 2. 上传按钮 -->
    <button id="btnUpload">上传文件</button>
    <br />
    <!-- 3. 显示上传到服务器上的图片 -->
    <img src="" alt="" id="img" width="800" />
  1. Verify that the file is selected
// 1. 获取上传文件的按钮
 var btnUpload = document.querySelector('#btnUpload')
 // 2. 为按钮添加 click 事件监听
 btnUpload.addEventListener('click', function() {
    
    
     // 3. 获取到选择的文件列表
     var files = document.querySelector('#file1').files
     if (files.length <= 0) {
    
    
         return alert('请选择要上传的文件!')
     }
     // ...后续业务逻辑
 })
  1. Append file to FormData
// 1. 创建 FormData 对象
 var fd = new FormData()
 // 2. 向 FormData 中追加文件
 fd.append('avatar', files[0])
  1. Use xhr to initiate a request to upload a file
// 1. 创建 xhr 对象
 var xhr = new XMLHttpRequest()
 // 2. 调用 open 函数,指定请求类型与URL地址。其中,请求类型必须为 POST
 xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
 // 3. 发起请求
 xhr.send(fd)
  1. Listen to the onreadystatechange event
xhr.onreadystatechange = function() {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
    var data = JSON.parse(xhr.responseText)
    if (data.status === 200) {
    
     // 上传文件成功
      // 将服务器返回的图片地址,设置为 <img> 标签的 src 属性
      document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url
    } else {
    
     // 上传文件失败
      console.log(data.message)
    }
  }
}

Show file upload progress :

  1. Import required libraries
<link rel="stylesheet" href="./lib/bootstrap.css" />
<script src="./lib/jquery.js"></script>
  1. Render progress bar based on Bootstrap
 	<!-- 进度条 -->
    <div class="progress" style="width: 500px; margin: 10px 0;">
      <div class="progress-bar progress-bar-info progress-bar-striped active" id="percent" style="width: 0%">
        0%
      </div>
    </div>
  1. Monitor upload progress events
	xhr.upload.onprogress = function(e) {
    
    
    if (e.lengthComputable) {
    
    
    // 1. 计算出当前上传进度的百分比
    var percentComplete = Math.ceil((e.loaded / e.total) * 100)
    $('#percent')
        // 2. 设置进度条的宽度
        .attr('style', 'width:' + percentComplete + '%')
        // 3. 显示当前的上传进度百分比
        .html(percentComplete + '%')
    }
 }
  1. Listen for upload completion events
	xhr.upload.onload = function() {
    
    
     $('#percent')
         // 移除上传中的类样式
         .removeClass()
         // 添加上传完成的类样式
         .addClass('progress-bar progress-bar-success')
 }

Advanced usage of jQuery

jQuery implements file upload

  1. Define the UI structure
<!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>

    <!-- 文件选择框 -->
    <input type="file" id="file1" />
    <!-- 上传文件按钮 -->
    <button id="btnUpload">上传</button>
  1. Verify that the file is selected
$('#btnUpload').on('click', function() {
    
    
     // 1. 将 jQuery 对象转化为 DOM 对象,并获取选中的文件列表
     var files = $('#file1')[0].files
     // 2. 判断是否选择了文件
     if (files.length <= 0) {
    
    
         return alert('请选择图片后再上传!‘)
     }
 })
  1. Append files to FormData
// 向 FormData 中追加文件
 var fd = new FormData()
 fd.append('avatar', files[0])
  1. Use jQuery to initiate a request to upload a file
 $.ajax({
    
    
     method: 'POST',
     url: 'http://www.liulongbin.top:3006/api/upload/avatar',
     data: fd,
     // 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
     contentType: false,
     // 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
     processData: false,
     success: function(res) {
    
    
         console.log(res)
     }
 })

jQuery realizes loading effect

  1. When an Ajax request starts, the ajaxStart function is executed. The loading effect can be displayed in the callback of ajaxStart
 // 自 jQuery 版本 1.8 起,该方法只能被附加到文档
 $(document).ajaxStart(function() {
    
    
     $('#loading').show()
 })
  1. When the Ajax request ends, execute the ajaxStop function. The loading effect can be hidden in the callback of ajaxStop
// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
 $(document).ajaxStop(function() {
    
    
     $('#loading').hide()
 })

axios

Axios is a library focused on network data requests.
Compared with the native XMLHttpRequest object, axios is simpler and easier to use.
Compared with jQuery, axios is more lightweight and only focuses on network data requests

Axios initiates a GET request

axios.get('url', { params: { /*参数*/ } }).then(callback)

// 请求的 URL 地址
 var url = 'http://www.liulongbin.top:3006/api/get'
 // 请求的参数对象
 var paramsObj = {
    
     name: 'zs', age: 20 }
 // 调用 axios.get() 发起 GET 请求
 axios.get(url, {
    
     params: paramsObj }).then(function(res) {
    
    
     // res.data 是服务器返回的数据
     var result = res.data
     console.log(res)
 })

Axios initiates a POST request

axios.post('url', { /*参数*/ }).then(callback)

// 请求的 URL 地址
 var url = 'http://www.liulongbin.top:3006/api/post'
 // 要提交到服务器的数据
 var dataObj = {
    
     location: '北京', address: '顺义' }
 // 调用 axios.post() 发起 POST 请求
 axios.post(url, dataObj).then(function(res) {
    
    
     // res.data 是服务器返回的数据
     var result = res.data
     console.log(result)
 })

Directly use axios to initiate a request

//语法
axios({
    
    
     method: '请求类型',
     url: '请求的URL地址',
     data: {
    
     /* POST数据 */ },
     params: {
    
     /* GET参数 */ }
 }) .then(callback)

//直接使用axios发起GET请求
axios({
    
    
     method: 'GET',
     url: 'http://www.liulongbin.top:3006/api/get',
     params: {
    
     // GET 参数要通过 params 属性提供
         name: 'zs',
         age: 20
     }
 }).then(function(res) {
    
    
     console.log(res.data)
 })

//直接使用axios发起POST请求
axios({
    
    
     method: 'POST',
     url: 'http://www.liulongbin.top:3006/api/post',
     data: {
    
     // POST 数据要通过 data 属性提供
         bookname: '程序员的自我修养',
         price: 666
     }
 }).then(function(res) {
    
    
     console.log(res.data)
 })

Homologous

Two pages have the same origin if their protocol, domain name and port are the same

Same Origin Policy

The same-origin policy is a security feature provided by browsers. JavaScript on website A does not allow resource interaction with non-same-origin website C.

  1. Unable to read Cookies, LocalStorage and IndexedDB of non-same-origin pages
  2. Unable to touch the DOM of non-same-origin pages
  3. Unable to send Ajax request to non-same-origin address

MDN's official concept: the same-origin policy restricts how documents or scripts loaded from the same source can interact with resources from another source. This is an important security mechanism for quarantining potentially malicious files.

cross domain

The same origin means that the protocols, domain names, and ports of the two URLs are the same. On the contrary, it is the
root cause of cross-domain cross-domain: the same-origin policy of the browser does not allow resource interaction between non-same-origin URLs.

Browser
interception of cross-domain requests Browsers allow cross-domain requests, but the data returned by cross-domain requests will be intercepted by the browser and cannot be obtained by the page!

How to implement cross-domain data requests

To achieve cross-domain data requests, the two main solutions are JSONP and CORS

JSONP: Appeared early and has good compatibility (compatible with lower versions of IE). It is a temporary solution that front-end programmers are forced to come up with in order to solve cross-domain problems. The disadvantage is that only GET requests are supported, not POST requests.

CORS: Appeared late, it is a W3C standard and is a fundamental solution to cross-domain Ajax requests. GET and POST requests are supported. The disadvantage is that it is not compatible with some low-version browsers

JSONP

Meaning : It is a "usage mode" of JSON, which can be used to solve the problem of cross-domain data access of mainstream browsers

Implementation principle : Due to the limitation of the browser's same-origin policy, it is not possible to request non-same-origin interface data through Ajax in web pages. but

Therefore, the realization principle of JSONP is to pass

Implementation principle of JSONP

<!--定义一个 success 回调函数-->
<script>
   function success(data) {
      
      
     console.log('获取到了data数据:')
     console.log(data)
   }
</script>
<!--通过 <script> 标签,请求接口数据-->
<script src="http://ajax.frontend.itheima.net:3006/api/jsonp?callback=success&name=zs&age=20"></script>

Disadvantages of JSONP

Since JSONP is passed

Note :There is no relationship between JSONP and Ajax, the method of JSONP requesting data cannot be called Ajax, because JSONP does not use the XMLHttpRequest object

JSONP in jQuery

The $.ajax() function provided by jQuery can not only initiate real Ajax data requests, but also initiate JSONP data requests. By default, using jQuery to initiate a JSONP request will automatically carry a parameter of callback=jQueryxxx, where jQueryxxx is a randomly generated callback function name

$.ajax({
    
    
    url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
    // 如果要使用 $.ajax() 发起 JSONP 请求,必须指定 datatype 为 jsonp
    dataType: 'jsonp',
    success: function(res) {
    
    
       console.log(res)
    }
 })

Custom parameters and callback function names

When using jQuery to initiate a JSONP request, if you want to customize JSONP parameters and callback function names, you can specify the following two parameters

$.ajax({
    
    
    url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
    dataType: 'jsonp',
    // 发送到服务端的参数名称,默认值为 callback
    jsonp: 'callback',
    // 自定义的回调函数名称,默认值为 jQueryxxx 格式
    jsonpCallback: 'abc',
    success: function(res) {
    
    
       console.log(res)
    }
 })

Implementation process of JSONP in jQuery

JSONP in jQuery also <script>implements cross-domain data access through the src attribute of the tag, but jQuery uses <script>the method of dynamically creating and removing tags to initiate a JSONP data request.

When initiating a JSONP request, <header>dynamically append a <script>tag to ;

After the JSONP request is successful, <header>dynamically remove <script> the tag that was appended just now;

Anti-Shake*

Anti-shake strategy: After the event is triggered, the callback will be executed after a delay of n seconds. If the event is triggered again within n seconds, the timing will be restarted.

When the user continuously enters a string of characters in the input box, the anti-shake strategy can be used to execute the query request only after the input is completed.This can effectively reduce the number of requests and save request resources

Anti-shake of the input box :

var timer = null                    // 1. 防抖动的 timer

 function debounceSearch(keywords) {
    
     // 2. 定义防抖的函数
    timer = setTimeout(function() {
    
    
    // 发起 JSONP 请求
    getSuggestList(keywords)
    }, 500)
 }

 $('#ipt').on('keyup', function() {
    
      // 3. 在触发 keyup 事件时,立即清空 timer
    clearTimeout(timer)
    // ...省略其他代码
    debounceSearch(keywords)
 })

List of suggestions for cached searches

  1. Define a global cache object
 // 缓存对象
  var cacheObj = {
    
    }
  1. Save search results into a cache object
// 渲染建议列表
 function renderSuggestList(res) {
    
    
    // ...省略其他代码
    // 将搜索的结果,添加到缓存对象中
    var k = $('#ipt').val().trim()
    cacheObj[k] = res
 }
  1. Prioritize getting search suggestions from the cache
// 监听文本框的 keyup 事件
 $('#ipt').on('keyup', function() {
    
    
    // ...省略其他代码

    // 优先从缓存中获取搜索建议
    if (cacheObj[keywords]) {
    
    
       return renderSuggestList(cacheObj[keywords])
    }
    // 获取搜索建议列表
    debounceSearch(keywords)
  })

throttling*

The throttling strategy (throttle) can reduce the firing frequency of events for a period of time.

Application Scenario

  • The mouse triggers an event (such as a click) continuously, and only triggers it once per unit time;
  • When lazy loading, it is necessary to monitor and calculate the position of the scroll bar, but it does not need to be triggered every time it slides, which can reduce the frequency of calculation without wasting CPU resources

Throttling case - mouse follow effect

  1. Render the UI structure and beautify the style
<!-- UI 结构 -->
<img src="./assets/angel.gif" alt="" id="angel" />
<style>
	/* CSS 样式 */
	html, body {
      
      
  		margin: 0;
  		padding: 0;
  		overflow: hidden;
	}
	#angel {
      
      
  		position: absolute;
	}
	</style>
  1. Implement mouse follow effect when not using throttling
$(function() {
    
    
   // 获取图片元素
   var angel = $('#angel')
   // 监听文档的 mousemove 事件
   $(document).on('mousemove', function(e) {
    
      // 设置图片的位置
      $(angel).css('left', e.pageX + 'px').css('top', e.pageY + 'px')
   })
})

Throttle concept

  • If the throttle valve is empty, it means that the next operation can be performed; if it is not empty, it means that the next operation cannot be performed.
  • After the current operation is completed, the throttle valve must be reset to empty, indicating that the next operation can be performed.
  • Before each operation, it must be judged whether the throttle valve is empty.

Optimizing mouse follow effects with throttling

$(function() {
    
    
  var angel = $('#angel')
  var timer = null // 1.预定义一个 timer 节流阀
  $(document).on('mousemove', function(e) {
    
    
    if (timer) {
    
     return } // 3.判断节流阀是否为空,如果不为空,则证明距离上次执行间隔不足16毫秒
    timer = setTimeout(function() {
    
    
      $(angel).css('left', e.pageX + 'px').css('top', e.pageY + 'px')
      timer = null // 2.当设置了鼠标跟随效果后,清空 timer 节流阀,方便下次开启延时器
    }, 16)
  })
})

The difference between anti-shake and throttling

  • Anti-shake: If the event is triggered frequently, the anti-shake can guarantee that == only the last trigger will take effect! == The previous N multiple triggers will be ignored!

  • Throttling: If events are fired frequently, throttling canReduce the frequency of event triggers, so the throttling isselectivelyPerform a part of the event!

HTTP protocol enhancement

Introduction to HTTP protocol

Communication :information transfer and exchange.

Three elements of communication:

  • subject of communication
  • Correspondence content
  • way of communication

Communication in the Internet
Case: The server sends the profile of Chuanzhi College to the client browser in response.
Among them,
the communicationThe principals are the server and the client browser;
communicativeThe content is the introduction of Chuanzhi College;
communicativeway is to respond

==Communication Protocol (Communication Protocol)== refers to the rules and agreements that the two parties must abide by to complete the communication. (such as envelopes)
Popular understanding : The two parties to the communication use the agreed format to send and receive messages. This pre-agreed communication format is called a communication protocol

The communication protocol in the Internet
needs to be implemented between the client and the serverweb contenttransmission, both parties to the communication must abide by theTransmission protocol for web content.
web content akaHypertext, so the transmission protocol of web content is also calledHypertext Transfer Protocol (HyperText Transfer Protocol), HTTP protocol for short

HTTP protocol
The HTTP protocol is the Hypertext Transfer Protocol (HyperText Transfer Protocol), which specifies the transmission format that must be followed when transmitting web page content between the client and the server.

  • The client submits data to the server in the format required by the HTTP protocol
  • The server should respond to the client with the content in the format required by the HTTP protocol

Interaction model of the HTTP protocol :

The HTTP protocol adopts an interaction model of == request/response ==

HTTP request

Since the HTTP protocol belongs to the communication protocol between the client browser and the server. therefore,client-initiated requestcalled == HTTP Request ==,Message sent by client to server, calledHTTP request message

Note: HTTP request message is also called HTTP request message.

The HTTP request message consists of four parts: request line, request header, blank line and request body.

insert image description here

  1. request line

The request line consists of three parts: request method, URL and HTTP protocol version, separated by spaces
insert image description here
insert image description here
2. Request header

The request header is used to describeThe basic information of the client, so as to inform the server of the relevant information of the client

For example: User-Agent is used to describe the current type of browser; Content-Type is used to describe the data format sent to the server; Accept is used to describe what type of returned content the client can receive; Accept-Language is used to describe the client Which human language text content the client expects to receive.

The request header consists of multiple lines==key/value pairs==, and the key and value of each line are separated by colons.

insert image description here
insert image description here

  1. blank line

The last request header field is followed by a blank line, informing the server that the request headers are over.
A blank line in the request message is used to separate the request header and the request body.
insert image description here

  1. Request Body
    The request body stores the data to be submitted to the server through POST
    insert image description here
    Note: Only POST requests have a request body, GET requests do not have a request body!

HTTP response

The response message is the content of the message that the server responds to the client, also called a response message.

HTTP response messageConsists of 状态行, 响应头部, 空行and 响应体4 parts

  • 状态行It consists of 3 parts: HTTP protocol version, status code and status code description text, separated by spaces
  • 响应头部Used to describe the basic information of the server. The response header consists of multiple lines of key/value pairs, and the key and value of each line are separated by colons in English
  • 空行After the end of the last response header field, there will be a blank line to inform the client that the response header is over. A blank line in the response message is used to separate the response header and response body.
  • 响应体Stored in is the resource content that the server responds to the client.

insert image description here

HTTP request method

The HTTP request method is part of the HTTP protocol. The function of the request method is to indicate the operation to be performed on the resources on the server. The most common request methods are GET and POST

insert image description here

HTTP response status code

HTTP response status code(HTTP Status Code), also part of the HTTP protocol,Used to identify the status of the response.
The response status code will be sent to the client browser along with the response message, and the browser can know whether the HTTP request is successful or failed based on the response status code returned by the server.

The HTTP status code consists of three decimal numbers. The first decimal number defines the type of the status code, and the last two numbers are used to subdivide the status code.
There are 5 types of HTTP status codes
insert image description here

2** Success-related response status codes

2** range of status codes, indicatingThe server has successfully received the request and processed it. Common 2** types of status codes are as follows:
insert image description here

3** Redirection-related response status codes

The status code in the range of 3** means thatServer asks client to redirect, further operations by the client are required to complete the resource request. Common 3** types of status codes are as follows:
insert image description here

4** Response status codes related to client errors

A status code in the range of 4**, indicatingThe client's request has illegal content, causing the request to fail. Common 4** types of status codes are as follows:
insert image description here

.5** Response status codes related to server errors

Status codes in the range of 5**, indicatingThe server failed to process the client's request normally and an unexpected error occurred. Common 5** types of status codes are as follows:
insert image description here

Git

The manual maintenance version has the following problems:
操作麻烦, 命名不规范, 容易丢失,协作困难

Version Control Software :
A system used to record changes to a document so that future revisions of a particular version can be viewed

Benefits of version control software :

  1. Easy to operate: You only need to memorize a few sets of simple terminal commands, and you can quickly get started with common version control software

  2. Easy to compare: Based on the functions provided by the version control software, it is convenient to compare the details of file changes, so as to find out the cause of the problem

  3. Easy backtracking: Selected files can be rolled back to a previous state, and even the entire project can be rolled back to a point in time in the past

  4. Not easy to lose: In the version control software, files deleted by users by mistake can be easily recovered

  5. Convenient collaboration: Based on the branching function provided by the version control software, code merging operations during multi-person collaborative development can be easily realized

Category :

  1. Local version control system: run on a single machine, making the operation of maintaining file versions a tool, and does not support multi-person collaborative development
    insert image description here
    Features:
  • Use software to record different versions of files, which improves work efficiency,
  • Reduced the error rate of manual maintenance versions

shortcoming:

  • Stand-alone operation, does not support multi-person collaborative development
  • After the version database fails, all historical update records will be lost
  1. Centralized version control system: typical representative SVN
    insert image description here

Features:

  • Server-based and client-side operating modes
  • The server keeps a record of all updates to the file
  • The client only keeps the latest file version

Advantages: network operation, support multi-person collaborative development

shortcoming:

  • Offline submission of version updates is not supported
  • After the central server crashed, everyone was not working
  • After the version database fails, all historical update records will be lost
  1. Distributed version control system: typical representative Git

Features: Based on server and client operating modes

  • The server saves all updated versions of the file
  • The client is a full backup of the server, not just the latest version of the file

advantage:

  • Network operation, support multi-person collaborative development
  • After the client is disconnected from the network, it supports offline local submission of version updates
  • Backups from any client can be used to recover after server failure or corruption

Git: Currently the most popular version control system

Open source, efficient management project version management, high performance, high availability

The reason why Git is fast and efficient mainly depends on its following two features :
Directly record snapshots instead of difference comparison
Almost all operations are performed locally

SVN diff comparison

Traditional version control systems such as SVN aredifference basedversion control, theyStores a base set of files and the cumulative differences of each file over time, can save disk space, but the disadvantage is that it is time-consuming and inefficient.

Git's record snapshot

Git snapshot is to regenerate a new file based on the original file version, similar to backup. For efficiency, if the file has not been modified, Git does not re-store the file, but only keeps a link pointing to the previously stored file.

Disadvantage : takes up a lot of disk space.
Advantage : version switching is very fast, because each version is a complete file snapshot, and the snapshot of the target version can be directly restored when switching versions.
Features : space for time

Most operations in Gitonly need to access local files and resources, generally does not require information from other computers on the network.

Features:
After the network is disconnected, the version management of the project can still be performed locally.
After the network is connected, the locally modified records can be synchronized to the cloud server.

Three areas in Git

Projects managed by Git have three areas, namely 工作区, 暂存区,Git 仓库

Modified : Indicates that the file has been modified, but the result of the modification has not been put into the temporary storage area.
Staged : Indicates that the current version of the modified file has been marked to include it in the next submission list.
Committed : Indicates that the file has been safely saved in the local Git repository

Basic Git workflow

  1. Modify files in the workspace
  2. Stage the changes you want to commit next time
  3. Submit the update, find the file in the staging area, and permanently store the snapshot to the Git repository

Git basics

Download link : https://git-scm.com/downloads

Common commands :

# 设置用户名
git config --global user.name "用户名"

# 设置邮件地址
git config --global user.email "邮件地址"

# 查看全局的配置信息
git config --list --global

# 查看指定的全局配置项
git config user.name
git config user.email

# 打开git config 命令的帮助手册
git help config

# 获取git config 命令的快速参考
git config -h

Two ways to get Git repository

  1. Convert an unversioned local directory into a Git repository
  2. Clone an existing Git repository from another server

Initialize the repository in an existing directory

If you have a project directory that has not been under version control and want to use Git to control it, you need to perform the following two steps:

  • In the project directory, open "Git Bash" by right mouse button
  • Execute the git init command to convert the current directory into a Git warehouse

The git init command will create a hidden directory named .git. This .git directory is the Git repository of the current project, which contains the initial necessary files, which are a necessary part of the Git repository.

git status: command to view the status of the file

git status -s: Show the status of the file in a compact way

git add index.html: Track new files (files newly added to the temporary storage area are preceded by a green A mark
)

git commit -m "提交消息": The file in the temporary storage area is waiting to be submitted to the Git warehouse for storage

insert image description here

Make changes to submitted files

Currently, the index.html file has been tracked by Git, and the contents of the index.html file in the workspace and the Git repository are consistent. After we modify the content of index.html in the workspace, run the git status and git status -s commands again,The file index.html appears under the line Changes not staged for commit, indicating that the content of the tracked file has changed, but it has not been placed in the temporary storage area

Note: There is a red M mark in front of the modified files that have not been put into the temporary storage area

Staging modified files

The index.html file in the workspace has been modified. If you want to temporarily save this modification, you need to run the git add command again. This command is a multifunctional command, which mainly has the following three functions:

  1. You can start tracking new files with
  2. Put the tracked and modified files into the temporary storage area
  3. Mark conflicting files as resolved

insert image description here

Commit staged files

Run the git commit -m "commit message" command again to submit the snapshot of index.html recorded in the temporary storage area to the Git warehouse for storage
insert image description here

Undo changes to a file

Undoing the modification to a file refers to restoring the modification to the corresponding file in the workspace to the version saved in the Git repository.
Result of the operation: all modifications will be lost and cannot be recovered! The risk is relatively high, please operate with caution!
The essence of the undo operation: Overwrite the specified file in the workspace with the file saved in the Git repository
insert image description here

Add multiple files at once to the staging area

If there are a lot of files that need to be temporarily stored, you can use the command git addto add all the newly added and modified files to the temporary storage area at one time

unstaged file

Remove the corresponding file from the staging area:git reset HEAD 要移除的文件名称

Skip using the staging area

The standard Git workflow is 工作区 → 暂存区 → Git 仓库, simplified 工作区 → Git 仓库, to submit changes in the workspace directly to the Git repository

Git provides a way to skip the use of the temporary storage area. As long as you add the -a option to git commit when submitting, Git will automatically store all tracked files and submit them together, thus skipping git add steps:git commit -a -m "描述消息"

remove file

There are two ways to remove files from a Git repository:

  • Remove corresponding files from Git repository and workspace at the same timegit rm -f index.js
  • Remove only the specified files from the Git repository, but keep the corresponding files in the workspacegit rm -cached index.css

insert image description here

ignore file

Some files don't need to be managed by Git, and you don't want them to always appear in the list of untracked files. In this case, we can create a configuration file named .gitignore that lists matching patterns for files to ignore: the
format specification for the file .gitignore is as follows:

  • Comments start with #
  • directories ending with /
  • Start with / to prevent recursion
  • Beginning with ! means negation
  • You can use glob patterns to match files and folders (glob refers to simplified regular expressions)

glob pattern

The so-called glob pattern refers to a simplified regular expression:

  1. Asterisk * matcheszero or more of any character
  2. [abc] matchesAny one of the characters listed in square brackets(this case matches an a or matches a b or matches a c)
  3. question mark ?matches only one character
  4. in square brackets usedashSeparate two characters, which means that all within the range of these two characters can be matched (such as [0-9] means to match all numbers from 0 to 9)
  5. Two asterisks ** means to match any intermediate directory (for example, a/**/z can match a/z, a/b/z or a/b/c/z, etc.)

insert image description here

View commit history

insert image description here

Fall back to the specified version

insert image description here

summary

The command to initialize the Git warehouse git init
The command to view the status of the file git status 或 git status -s
The command to add the file to the temporary storage area at one time The git add
command to submit the file in the temporary storage area to the Git warehousegit commit -m "提交消息"

Guess you like

Origin blog.csdn.net/qq_45699150/article/details/126733744