Ajax zero-based entire gitt core content full set

1.5 Query string

2. The nature of the parameters carried by the get request

Regardless of using $.ajax(), $.get(), or directly using the xhr object to initiate a GET request, when parameters need to be carried, in essence, the parameters are directly appended to the query string in the form of After the URL address, it is sent to the server.

$.get('url', {
    
    name: 'zs', age: 20}, function() {
    
    }) 
// 等价于 $.get('url?name=zs&age=20', function() {
    
    }) 
 $.ajax({
    
     method: 'GET', url: 'url', data: {
    
    name: 'zs', age: 20}, success: function() {
    
    } }) 
// 等价于 $.ajax({
    
     method: 'GET', url: 'url?name=zs&age=20', success: function() {
    
    } }) 

1.6 URL encoding and decoding

what is url encoding
insert image description here

http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记l
经过URL编码之后,URL地址变成了如下格式:
http://w.liulongbin.top:3006/api/getbooks?id=1&bookname=8E88A58BF8卫63B88B8%E8%AE8B0

insert image description here
3. Precautions for URL encoding
Since the browser will automatically encode the URL address, in most cases, programmers do not need to care about the encoding and decoding operations of the URL address.

1.7 Use xhr to send post requests

insert image description here

// 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)
    }
}

2. Data exchange format

insert image description here

2.1xml and html

insert image description hereDifference:
Although both XML and HTML are markup languages, there is no relationship between them.
HTML is designed to describe the content on the webpage and is the carrier of webpage content
XML is designed to transmit and store data and is the carrier of data

2.2json

Concept: The full English name of JSON is JavaScript Object Notation, that is, "JavaScript Object Notation". Simply put, 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.
Function: JSON is a lightweight text data exchange format, similar to XML in function, specially used for storing and transmitting data, but JSON is smaller, faster and easier to parse than XML.
Status: JSON is a data format that was promoted and used in 2001. So far, JSON has become the mainstream data exchange format.
JSON is the use of strings to represent Javascript objects and arrays. Therefore, JSON contains two structures, object and array. Through the mutual nesting of these two structures, various complex data structures can be represented.

2.1 Data structure

The data inside cannot be undefined, function and other non-existing values, and must be selected from 6 types

insert image description here
insert image description here
insert image description here

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.

4.1 Understanding XMLHttpRequest Level

  1. Disadvantages of the old version of XMLHttpRequest
    Only supports the transmission of text data, and cannot be used to read and upload files
    . When transmitting and receiving data, there is no progress information, and only prompts whether it is completed
  2. The new function of XMLHttpRequest Level2
    can set the time limit of HTTP request,
    can use FormData object to manage form data,
    can upload files,
    and can get the progress information of data transmission

4.3 FormData object management 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.append appends one by one

   // 1. 新建 FormData 对象
      var fd = new FormData()
      // 2. 为 FormData 添加表单项
      fd.append('uname', 'zs')
      fd.append('upwd', '123456')
      // 3. 创建 XHR 对象
      var xhr = new XMLHttpRequest()
      // 4. 指定请求类型与URL地址
      xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
      // 5. 直接提交 FormData 对象,这与提交网页表单的效果,完全一样
      xhr.send(fd)

2. Use the filled form, directly use the form as a parameter of formdata, and the data will be automatically filled into formdata

 // 获取表单元素
 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() {
    
    }
})

4.4 Upload files

The new XMLHttpRequest object can not only send text information, but also upload files.
Implementation steps:
define the UI structure,
verify whether the file is selected,
append the file to FormData,
use xhr to initiate a request to upload the file,
and listen to the onreadystatechange event

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" />

2. Verify that the data 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('请选择要上传的文件!')
     }
     // ...后续业务逻辑
 })

3. Add files to FormData

 // 1. 创建 FormData 对象
 var fd = new FormData()
 // 2. 向 FormData 中追加文件
 fd.append('avatar', files[0])

4. Use xhr to initiate a file upload request

 // 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)

5. 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)
    }
  }
}

4.5 Display file upload progress

In the new version of the XMLHttpRequest object, you can get the upload progress of the file by listening to the xhr.upload.onprogress event. The syntax format is as follows:

 // 创建 XHR 对象
 var xhr = new XMLHttpRequest()
 // 监听 xhr.upload 的 onprogress 事件
 xhr.upload.onprogress = function(e) {
    
    
    // e.lengthComputable 是一个布尔值,表示当前上传的资源是否具有可计算的长度
    if (e.lengthComputable) {
    
    
        // e.loaded 已传输的字节
        // e.total  需传输的总字节
        var percentComplete = Math.ceil((e.loaded / e.total) * 100)
    }
 }

Rendering with Bootstrap progress bar Rendering
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>

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 + '%')
    }
 }

Listen for upload completion events

 xhr.upload.onload = function() {
    
    
     $('#percent')
         // 移除上传中的类样式
         .removeClass()
         // 添加上传完成的类样式
         .addClass('progress-bar progress-bar-success')
 }

5. Communication protocol

Communication Protocol (Communication Protocol) refers to the rules and agreements that the two parties must abide by to complete the communication.
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.

Communication protocol in the Internet
To realize the transmission of webpage content between the client and the server, both parties must abide by the transmission protocol of webpage content.
Web page content is also called hypertext, so the transfer protocol of web page content is also called HyperText Transfer Protocol (HyperText Transfer Protocol), referred to as HTTP protocol.
Since the HTTP protocol belongs to the communication protocol between the client browser and the server. Therefore, the request initiated by the client is called an HTTP request, and the message sent by the client to the server is called an HTTP request message.

insert image description here
insert image description here
insert image description hereinsert image description here
insert image description hereinsert image description hereinsert image description here
insert image description here
insert image description hereinsert image description here
insert image description hereinsert image description here
insert image description here

insert image description here

insert image description here

insert image description hereinsert image description here
insert image description hereinsert image description here

git

insert image description here
insert image description here
insert image description hereinsert image description here
insert image description here

git add. Put the newly added and modified files into the temporary storage area
insert image description hereinsert image description here
insert image description hereinsert image description here
insert image description hereinsert image description here

insert image description here

insert image description here
insert image description hereinsert image description here===========================================

insert image description here

Guess you like

Origin blog.csdn.net/qq_42373007/article/details/127916356