Zero, article directory
Front-end and back-end interaction 3, Ajax enhancement
1. Basic use of XMLHttpRequest
(1) What XMLHttpRequest
XMLHttpRequest
(xhr for short) is a Javascript object provided by the browser, through which you can请求服务器上的数据资源
.jQuery
Ajax
The function inxhr
object. is encapsulated based on the
(2) Use xhr to initiate a GET request
- Create xhr object
- Call the xhr.open() function
- Call the xhr.send() function
- Listen to the xhr.onreadystatechange event
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('GET', 'http://xxx.yyy.zzz/api/getbooks')
// 3. 调用 send 函数
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取服务器响应的数据
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
(3) Understand the readyState attribute of the xhr object
XMLHttpRequest
readyState
The attribute of the request must be in one of the following states:Ajax
request. Each object is used to indicate the status of the currentAjax
value | state | describe |
---|---|---|
0 | UNSENT | The XMLHttpRequest object has been created, but the open method has not been called yet. |
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 | Data is being received, and the response attribute already contains some data. |
4 | DONE | The Ajax request is complete, which means the data transfer has completely completed or failed. |
(4) Use xhr to initiate a GET request with parameters
- When using an xhr object to initiate a GET request with parameters, you only need to specify parameters for the URL address during the call to xhr.open.
- The parameter spliced after the URL address is called
查询字符串
.
// ...省略不必要的代码
xhr.open('GET', 'http://xxx.yyy.zzz/api/getbooks?id=1')
// ...省略不必要的代码
(5) Query string
- Definition: A query string (URL parameter) is a string (variable) added to the end of the URL that is used to send information to the server.
- Format: Put the English
?
at the end of the URL, and then add参数=值
. If you want to add multiple parameters, use a>&
symbols to separate. In this form, you can add the data you want to send to the server to the URL.
// 不带参数的 URL 地址
http://xxx.yyy.zzz/api/getbooks
// 带一个参数的 URL 地址
http://xxx.yyy.zzz/api/getbooks?id=1
// 带两个参数的 URL 地址
http://xxx.yyy.zzz/api/getbooks?id=1&bookname=西游记
- The nature of the parameters carried in the GET request: whether using
$.ajax()
, using$.get()
, or directly using the xhr object to initiateGET
When a request needs to carry parameters, in essence, the parameters are sent directly to the server in the form of查询字符串
,追加到 URL 地址的后面
.
$.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() {
} })
(6) What is URL encoding
- For HTTP related knowledge, please refer toHTTP Detailed Explanation, which contains detailed
URL编码
instructions. - Only English-related letters, punctuation marks, and numbers are allowed to appear in the URL address. Therefore, Chinese characters are not allowed to appear in the URL address.
- If the URL needs to contain characters like Chinese, the Chinese characters must be
编码(转义)
modified. Due to the浏览器会自动对 URL 地址进行编码
operation, in most cases, programmers do not need to care about the encoding and decoding operations of URL addresses.
http://xxx.yyy.zzz/api/getbooks?id=1&bookname=西游记
// 经过 URL 编码之后,URL地址变成了如下格式:
http://xxx.yyy.zzz/api/getbooks?id=1&bookname=%E8%A5%BF%E6%B8%B8%E8%AE%B0
- The browser provides URL encoding and decoding APIs, which are:
encodeURI()
encoded functiondecodeURI()
decoding function
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
var str = '张三'
var str2 = encodeURI(str)
console.log(str2) //%E5%BC%A0%E4%B8%89
var str3 = decodeURI('%E5%BC%A0%E4%B8%89')
console.log(str3) //张三
</script>
</body>
</html>
(7) Use xhr to initiate a POST request
- Create xhr object
- Call the xhr.open() function
- Set the Content-Type attribute (fixed writing method)
- Call the xhr.send() function and specify the data to be sent
- Listen to the xhr.onreadystatechange event
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('POST', 'http://xxx.yyy.zzz/api/addbook')
// 3. 设置 Content-Type 属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
// 5. 监听事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
2. Data exchange format
(1) What is the data exchange format?
- 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 often mentioned are
XML 和 JSON
. Among them, XML is rarely used, so the data exchange format we重点
need to learn isJSON
.
(2)XML
- The full English name of XML is EXtensible Markup Language, which is extensible markup language. Therefore, XML, like HTML, is a markup language.
-
Although XML and HTML are both markup languages, there is no relationship between them.
- HTML is designed to describe the content on web pages and is the carrier of web content.
- XML is designed to transmit and store data and is the carrier of data
-
Disadvantages of XML: bloated format, many codes unrelated to data, large volume, and low transmission efficiency. Parsing XML in Javascript is cumbersome
(3)JSON
- What is JSON
- Concept: The full English name of JSON is JavaScript Object Notation, which is "
JavaScript 对象表示法
". It uses文本表示一个 JS 对象或数组的信息
, therefore,JSON 的本质是字符串
. - Role: JSON is a type
轻量级的文本数据交换格式
that is similar to XML in its role and is specifically used to store and transmit data, but JSON is smaller, faster, and easier to parse than XML. - Current situation: JSON is a data format that began to be promoted and used in 2001, and up to now,
JSON 已经成为了主流的数据交换格式
.
- Concept: The full English name of JSON is JavaScript Object Notation, which is "
//这是一个对象
var obj = {
a: 'Hello', b: 'World'}
//这是一个 JSON 字符串,本质是一个字符串
var json = '{"a": "Hello", "b": "World"}'
- Two structures of JSON: JSON contains two structures:
对象
and数组
. Through these two structures,相互嵌套
, can represent various complex data structures.- Object structure:
对象结构
is represented in JSON as a key-value pair structure of{ key: value, key: value, … }
.key
must be a string using英文的双引号包裹
,value
can have 6 data types:数字、字符串、布尔值、null、数组、对象
type. - Array structure:
数组结构
is represented as[ "java", "javascript", 30, true … ]
in JSON. The types of data in the array can be数字、字符串、布尔值、null、数组、对象
6 types.
- Object structure:
//对象
{
"name": "zs",
"age": 20,
"gender": "男",
"address": null,
"hobby": ["吃饭", "睡觉", "打豆豆"]
}
//数组
[ "java", "python", "php" ]
[ 100, 200, 300.5 ]
[ true, false, null ]
[ {
"name": "zs", "age": 20}, {
"name": "ls", "age": 30} ]
[ [ "苹果", "榴莲", "椰子" ], [ 4, 50, 5 ] ]
-
JSON syntax considerations
-
Property names must be wrapped in double quotes
-
String type values must be wrapped in double quotes
-
Single quotes are not allowed for strings in JSON
-
Comments cannot be written in JSON
-
The outermost layer of JSON must be in object or array format
-
Cannot use undefined or functions as JSON values
-
-
Conversion between JSON and JS objects
JSON.parse()
:Convert from JSON string to JS objectJSON.stringify()
:Convert from JS object to JSON string
var obj = JSON.parse('{"a": "Hello", "b": "World"}')
//结果是 {a: 'Hello', b: 'World'}
var json = JSON.stringify({
a: 'Hello', b: 'World'})
//结果是 '{"a": "Hello", "b": "World"}'
- Serialization and deserialization
- Serialization: The process of converting
数据对象
to字符串
is called序列化
, for example: calling JSON.stringify( ) function operation is called JSON serialization. - Deserialization: The process of converting
字符串
into数据对象
is called反序列化
, for example: calling JSON.parse The operation of () function is called JSON deserialization.
- Serialization: The process of converting
3. Encapsulate your own Ajax function
(1) Effect to be achieved
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<script src="./js/myajax.js"></script>
</head>
<body>
<script>
myajax({
method: 'GET',
url: 'http://xxx.yyy.zzz/api/getbooks',
data: {
id: 1
},
success: function(res) {
console.log(res)
}
})
myajax({
method: 'post',
url: 'http://xxx.yyy.zzz/api/addbook',
data: {
bookname: '水浒传',
author: '施耐庵',
publisher: '北京图书出版社'
},
success: function(res) {
console.log(res)
}
})
</script>
</body>
</html>
(2) Define options parameter options
- The myajax() function is our custom Ajax function. It receives a configuration object as a parameter. The following attributes can be configured in the configuration object:
- method: type of request
- url: requested URL address
- data: the data carried by the request
- success: callback function after the request is successful
(3) Define the myajax function
- resolveData(): Convert the data object into query string format and submit it to the server.
- myajax(): Create xhr object and listen to onreadystatechange event
- Different request types correspond to different operations of the xhr object, so it is necessary to judge the request type if...else...
function resolveData(data) {
var arr = []
for (var k in data) {
var str = k + '=' + data[k]
arr.push(str)
}
return arr.join('&')
}
function myajax(options) {
var xhr = new XMLHttpRequest()
// 把外界传递过来的参数对象,转换为 查询字符串
var qs = resolveData(options.data)
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)
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
options.success(result)
}
}
}
4. New features of XMLHttpRequest Level2
(1) Understand XMLHttpRequest Level2
-
Disadvantages of the old 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, only a prompt whether it is completed or not.
-
New features of XMLHttpRequest Level2
- You can set the timeout for HTTP requests
- Form data can be managed using the FormData object
- Can upload files
- Obtain progress information of data transfer
(2) Set HTTP request time limit
- Sometimes, Ajax operations are time-consuming and there is no telling how long they will take. If the network speed is very slow, users may have to wait for a long time. The new version of the XMLHttpRequest object adds the timeout attribute, which allows you to set the timeout period for HTTP requests:
xhr.timeout = 3000
- The above statement sets the maximum wait time to 3000 milliseconds. After this time limit, HTTP requests will be automatically stopped. There is also a timeout event to specify the callback function:
xhr.ontimeout = function(event){
alert('请求超时!')
}
(3) FormData object manages form data
- Ajax operations are often used to submit form data. In order to facilitate form processing, HTML5 adds a new FormData object that 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://xxx.yyy.zzz/api/formdata')
// 5. 直接提交 FormData 对象,这与提交网页表单的效果,完全一样
xhr.send(fd)
- The FormData object can also be used to obtain the value of a web form. The sample code is as follows:
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<form id="form1">
<input type="text" name="uname" autocomplete="off" />
<input type="password" name="upwd" />
<button type="submit">提交</button>
</form>
<script>
// 1. 通过 DOM 操作,获取到 form 表单元素
var form = document.querySelector('#form1')
form.addEventListener('submit', function(e) {
// 阻止表单的默认提交行为
e.preventDefault()
// 创建 FormData,快速获取到 form 表单中的数据
var fd = new FormData(form)
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://xxx.yyy.zzz/api/formdata')
xhr.send(fd)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
})
</script>
</body>
</html>
(4) Upload files
-
The new XMLHttpRequest object can not only send text messages, but also upload files. Implementation steps:
- Define UI structure
- Verify that file is selected
- Append files to FormData
- Use xhr to initiate a file upload request
- Listen to the onreadystatechange event
-
Define UI structure
<!-- 1. 文件选择框 -->
<input type="file" id="file1" />
<!-- 2. 上传按钮 -->
<button id="btnUpload">上传文件</button>
<br />
<!-- 3. 显示上传到服务器上的图片 -->
<img src="" alt="" id="img" width="800" />
- Verify that 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('请选择要上传的文件!')
}
// ...后续业务逻辑
})
- Append files to FormData
// 1. 创建 FormData 对象
var fd = new FormData()
// 2. 向 FormData 中追加文件
fd.append('avatar', files[0])
- Use xhr to initiate a file upload request
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,指定请求类型与URL地址。其中,请求类型必须为 POST
xhr.open('POST', 'http://xxx.yyy.zzz/api/upload/avatar')
// 3. 发起请求
xhr.send(fd)
- Listen to 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://xxx.yyy.zzz' + data.url
} else {
// 上传文件失败
console.log(data.message)
}
}
}
(5) Display file upload progress
- In the new version of the XMLHttpRequest object, you can obtain the file upload progress 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)
}
}
- Import the required libraries
<link rel="stylesheet" href="./lib/bootstrap.css" />
<script src="./lib/jquery.js"></script>
- 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. Advanced usage of jQuery
(1) jQuery implements file upload
- Define UI structure
<!-- 导入 jQuery -->
<script src="./lib/jquery.js"></script>
<!-- 文件选择框 -->
<input type="file" id="file1" />
<!-- 上传文件按钮 -->
<button id="btnUpload">上传</button>
- Verify that file is selected
$('#btnUpload').on('click', function() {
// 1. 将 jQuery 对象转化为 DOM 对象,并获取选中的文件列表
var files = $('#file1')[0].files
// 2. 判断是否选择了文件
if (files.length <= 0) {
return alert('请选择图片后再上传!‘)
}
})
- Append files to FormData
// 向 FormData 中追加文件
var fd = new FormData()
fd.append('avatar', files[0])
- Use jQuery to initiate a request to upload a file
$.ajax({
method: 'POST',
url: 'http://xxx.yyy.zzz/api/upload/avatar',
data: fd,
// 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
contentType: false,
// 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
processData: false,
success: function(res) {
console.log(res)
}
})
(2) jQuery implements loading effect
ajaxStart(callback)
: When Ajax request开始
, execute the ajaxStart function. The loading effect can be displayed in the callback of ajaxStart.- Note: The $(document).ajaxStart() function will listen to all Ajax requests in the current document.
// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
$(document).ajaxStart(function() {
$('#loading').show()
})
ajaxStop(callback)
: When Ajax request结束
, execute the ajaxStop function. You can hide the loading effect in the callback of ajaxStop.
// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
$(document).ajaxStop(function() {
$('#loading').hide()
})
6、Axios
(1) What is Axios
- Axios is
专注于网络数据请求
's place. - Compared to the native XMLHttpRequest object, axios
简单易用
. - Compared with jQuery, axios
更加轻量化
only focuses on network data requests.
(2) axios initiates a GET request
- grammar:
axios.get('url', { params: { /*参数*/ } }).then(callback)
// 请求的 URL 地址
var url = 'http://xxx.yyy.zzz/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)
})
(3) axios initiates a POST request
- grammar:
axios.post('url', { /*参数*/ }).then(callback)
// 请求的 URL 地址
var url = 'http://xxx.yyy.zzz/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)
})
(4) Directly use axios to initiate a request
- axios also provides functions similar to $.ajax() in jQuery, with the following syntax:
axios({
method: '请求类型',
url: '请求的URL地址',
data: {
/* POST数据 */ },
params: {
/* GET参数 */ }
}) .then(callback)
- Directly use axios to initiate a GET request
axios({
method: 'GET',
url: 'http://xxx.yyy.zzz/api/get',
params: {
// GET 参数要通过 params 属性提供
name: 'zs',
age: 20
}
}).then(function(res) {
console.log(res.data)
})
- Directly use axios to initiate a POST request
axios({
method: 'POST',
url: 'http://xxx.yyy.zzz/api/post',
data: {
// POST 数据要通过 data 属性提供
bookname: '程序员的自我修养',
price: 666
}
}).then(function(res) {
console.log(res.data)
})