5-Ajax


5-1 Basics

1. server

Server: The computer responsible for storing and providing external resources during the online process.

Client: The computer responsible for obtaining and consuming resources during the Internet access process.

2.URL address

Uniform Resource Locator.

Examples of common URLs:

http://www.baidu.com

A URL address generally consists of three parts:

① Communication protocol between client and server

② The name of the server where the resource is stored

③ The specific storage location of the resource on the server

1675438793872

3.Ajax

The full name of Ajax is Asynchronous Javascript And XML (asynchronous JavaScript and XML).

Popular understanding: Ajax is the way to use the XMLHttpRequest object to interact with the server in the web page .

Ajax in jQuery

The usage of XMLHttpRequest provided by the browser is relatively complicated, so jQuery encapsulates XMLHttpRequest and provides a series of Ajax-related functions, which greatly reduces the difficulty of using Ajax.

The three most commonly used methods for initiating Ajax requests in jQuery are as follows:

  • $.get()
  • $.post()
  • $.ajax()

3.1 Syntax of $.get() function

$.get(url, [data], [callback])//可不带参数data
    
//[]为可选参数  
$.get('http://www.liulongbin.top:3006/api/getbooks', {
    
     id: 1 }, function(res) {
    
    
    console.log(res);
})
parameter name Parameter Type Is it required? illustrate
url string yes The address of the resource to request
data object no Parameters to be carried during resource request. (Query conditions)
callback function no The callback function when the request is successful, and the parameter is the corresponding data of the server.

3.2 Syntax of $.post() function

$.post(url, [data], [callback])

$.post(   'http://www.liulongbin.top:3006/api/addbook', // 请求的URL地址
   {
    
     bookname: '水浒传', author: '施耐庵', publisher: '上海图书出版社' }, // 提交的数据
   function(res) {
    
     // 回调函数
      console.log(res)
   }
)

parameter name Parameter Type Is it required? illustrate
url string yes Address to submit data
data object no data to submit
callback function no Callback function when the data is submitted successfully

3.3 Syntax of $.ajax() function

Compared with the $.get() and $.post() functions, the $.ajax() function provided in jQuery is a more comprehensive function that allows us to configure Ajax requests in more detail.

$.ajax({
    
    
   type: '', // 请求的方式,例如 GET 或 POST
   url: '',  // 请求的 URL 地址
   data: {
    
     },// 这次请求要携带的数据
   success: function(res) {
    
     } // 请求成功之后的回调函数
})

5-2 form form and template engine

1. Properties of the form

Attributes value describe
action URL address Specifies where to send form data when the form is submitted. The default value is the URL address of the current page.
method get or post Specifies how to submit form data to the action URL. 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.
enctype application/x-www-form-urlencoded multipart/form-data text/plain Specifies how to encode form data before sending it
target _blank _self _parent _top framename Specifies where to open the action URL
value describe
_blank Opens in a new window.
_self default. Open in the same frame.
_parent Opens in the parent frameset. (Rarely used)
_top Open in full window. (Rarely used)
framename Open in the specified frame. (Rarely used)
value describe
application/x-www-form-urlencoded encode all characters before sending (default)
multipart/form-data Characters are not encoded. This value must be used when using forms that include a file upload control.
text/plain Spaces are converted to "+" plus signs, but special characters are not encoded. (Rarely used)

Note :

  • When the form is submitted, the page will immediately jump to the URL specified by the action attribute.
  • The get method is suitable for submitting a small amount of simple data.
  • The post method is suitable for submitting a large amount of, complex, or data that includes file uploads.
  • In actual development, the post submission method of the form is used most, and get is rarely used. For example, form operations such as login, registration, and adding data, all need to use the post method to submit the form.
  • 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!

2. Synchronous submission of forms

Clicking the submit button triggers the form submission operation, so that the page jumps to the action URL, which is called synchronous submission of the form.

shortcoming:

①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.

②After the form is submitted synchronously, the previous state and data of the page will be lost .

3. Submit form data via ajax

3.1 Listening to form submission events

$('#form1').submit(function(e) {
    
    
   alert('监听到了表单的提交事件')
})

$('#form1').on('submit', function(e) {
    
    
   alert('监听到了表单的提交事件')
})

3.2 Prevent form default submission behavior

$('#form1').submit(function(e) {
    
    
   // 阻止表单的提交和页面的跳转
   e.preventDefault()
})

$('#form1').on('submit', function(e) {
    
    
   // 阻止表单的提交和页面的跳转
   e.preventDefault()
})

3.3 Quickly get the data in the form

$(selector).serialize()//可以一次性获取到表单中的所有的数据。

example:

<form id="form1">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <button type="submit">提交</button>
</form>
$('#form1').serialize()
// 调用的结果:
// username=用户名的值&password=密码的值

Note: When using the serialize() function to quickly get form data, you must add a name attribute to each form element

5-3 Ajax enhancement (native js)

1.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.

1.1 Use xhr to initiate a GET request

// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,指定 请求方式 与 URL地址
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')

xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
//这种在 URL 地址后面拼接的参数,叫做查询字符串。(?id=1)

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

1.2 readyState attribute

value state describe
0 UNSENT The XMLHttpRequest object has been created, but the open method has not been called.
1 OPENED The open() method has been called.
2 HEADERS_RECEIVED The send() method has been called and the response headers have been received.
3 LOADING During data reception, the response attribute already contains some data.
4 DONE The Ajax request completes, which means the data transfer has completely completed or failed.

1.3 Query string

Definition: A query string (URL parameter) is a string (variable) that is appended to the end of the URL to send information to the server.

Format: put English ? at the end of the URL, and then add parameter =value . If you want to add multiple parameters, use & 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=西游记
$.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.4 URL encoding and decoding

Chinese "==" character

encodeURI('汉字')  编码的函数
decodeURI('编码')  解码的函数

1.5XMLHttpRequest use

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

2. Data exchange format

​ The data exchange format is the format for data transmission and exchange between the server and the client . (XML, JSON, etc.)

2.1 Two structures of JSON

//对象结构
{key:value} key用双引号,value字符串用双引号
value 的数据类型可以是数字、字符串、布尔值、null、数组、对象6种类型。
{
    "name": "zs",
    "age": 20,
    "gender": "男",
    "address": null,
    "hobby": ["吃饭", "睡觉", "打豆豆"]
}

//数据结构  
[ , , ]用逗号隔开
数组中数据的类型可以是数字、字符串、布尔值、null、数组、对象6种类型。
[ "java", "python", "php" ]
[ 100, 200, 300.5 ]
[ true, false, null ]
[ { "name": "zs", "age": 20}, { "name": "ls", "age": 30} ]
[ [ "苹果", "榴莲", "椰子" ], [ 4, 50, 5 ] ]

2.2JSON and JS objects

the difference:

//这是一个对象
var obj = {
    
    a: 'Hello', b: 'World'}

//这是一个 JSON 字符串,本质是一个字符串
var json = '{"a": "Hello", "b": "World"}' 

Interchange:

//JSON->JS对象(JSON反序列化)
var obj = JSON.parse('{"a": "Hello", "b": "World"}')
//结果是 {a: 'Hello', b: 'World'}

//JS对象->JSON(JSON序列化)
var json = JSON.stringify({
    
    a: 'Hello', b: 'World'})
//结果是 '{"a": "Hello", "b": "World"}'

3. New features of XMLHttpRequest Level2

Old version:

①Only supports the transmission of text data, and cannot be used to read and upload files

② When sending and receiving data, there is no progress information, only a prompt whether it is completed or not

new version:

① You can set the time limit for HTTP requests

② You can use the FormData object to manage form data

③You can upload files

④ The progress information of data transmission can be obtained

3.1 Set the HTTP request time limit

Sometimes, Ajax operations are time-consuming, and it's unpredictable how long it will take. If the network speed is slow, users may have to wait a long time. The new version of the XMLHttpRequest object adds the timeout attribute, which can set the time limit of the HTTP request:

 xhr.timeout = 3000
/*上面的语句,将最长等待时间设为 3000 毫秒。过了这个时限,就自动停止HTTP请求。与之配套的还有一个 timeout 事件,用来指定回调函数:*/
 xhr.ontimeout = function(event){
    
    
     alert('请求超时!')
 }

3.2 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. 新建 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)

The FormData object can also be used to obtain the value of the web form, the sample code is as follows:

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

3.3 Upload files

Implementation steps:

① Define the UI structure

    <!-- 1. 文件选择框 -->
    <input type="file" id="file1" />
    <!-- 2. 上传按钮 -->
    <button id="btnUpload">上传文件</button>
    <br />
    <!-- 3. 显示上传到服务器上的图片 -->
    <img src="" alt="" id="img" width="800" />

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

③Add files to FormData

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

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

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

⑥ Display file upload progress (jquery+bootstrap)

 // 创建 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)
        //渲染
        //……
    }
 }
//监听上传完成
   
 xhr.upload.onload = function() {
    
    
     $('#percent')
         // 移除上传中的类样式
         .removeClass()
         // 添加上传完成的类样式
         .addClass('progress-bar progress-bar-success')
 }

4. Advanced JQuery (JQuery implements file upload)

Implementation steps:

① Define the UI structure

②Verify whether the file is selected

③Add files to FormData

④ Use jQuery to initiate a file upload request

 $.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 the loading effect (circle)

When an Ajax request starts , the ajaxStart function is executed. The loading effect can be displayed in the callback of ajaxStart, the sample code is as follows:

// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
 $(document).ajaxStart(function() {
    
    
     $('#loading').show()
 })
//注意: $(document).ajaxStart() 函数会监听当前文档内所有的 Ajax 请求。

When the Ajax request ends , execute the ajaxStop function. The loading effect can be hidden in the callback of ajaxStop, the sample code is as follows:

 // 自 jQuery 版本 1.8 起,该方法只能被附加到文档
 $(document).ajaxStop(function() {
    
    
     $('#loading').hide()
 })

5.axios

Axios is a library focused on network data requests .

Compared with the native XMLHttpRequest object, axios is easier to use .

Compared with jQuery, axios is more lightweight and only focuses on network data requests.

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

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

3. Directly use axios to initiate a request

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


   

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

5-4 Cross domain and JSONP

1. Same origin and cross-domain

1.1 Homology

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

Same Origin Policy: It is a security feature provided by browsers. Interaction of resources between non-same-origin URLs is not allowed, limiting how a document or script loaded from the same origin can interact with a resource from another origin. This is an important security mechanism for quarantining potentially malicious files.

1.2 Cross domain

URLs that are not of the same origin are cross-domain.

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.

Realize cross-domain data request: JSONP, 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 the fundamental solution for cross-domain Ajax requests. GET and POST requests are supported. The disadvantage is that it is not compatible with some low-version browsers.

2.JSONP

2.1 Principle

Due to the limitation of the same-origin policy of the browser, it is not possible to request non-same-origin interface data through Ajax in the webpage. but

Therefore, the realization principle of JSONP is to pass

Implement simple 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>

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.

2.2 JSONP in Jquery

The $.ajax() function provided by jQuery can not only initiate real Ajax data requests, but also initiate JSONP data requests, for example:

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

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.

Custom parameters and callback functions:

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

Implementation process:

insert image description here

Guess you like

Origin blog.csdn.net/qq_51444138/article/details/129310199