1.XMLHttpRequest
1.1使用xhr发起get请求
// 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)
}
}
1.2xhr对象的readyState属性
readyState:当前 Ajax 请求所处的状态
值 | 状态 | 描述 |
0 | UNSENT | XMLHttpRequest 对象已被创建,但尚未调用 open方法。 |
1 | OPENED | open() 方法已经被调用。 |
2 | HEADERS_RECEIVED | send() 方法已经被调用,响应头也已经被接收。 |
3 | LOADING | 数据接收中,此时 response 属性中已经包含部分数据。 |
4 | DONE | Ajax 请求完成,这意味着数据传输已经彻底完成或失败。 |
1.3使用xhr发起带参数的GET请求
// ...省略不必要的代码
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
// ...省略不必要的代码
这种在 URL 地址后面拼接的参数,叫做查询字符串。
1.4 查询字符串
// 不带参数的 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=西游记
1.5 URL编码与解码
encodeURI() 编码的函数
decodeURI() 解码的函数
encodeURI('黑马程序员')
// 输出字符串 %E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98
decodeURI('%E9%BB%91%E9%A9%AC')
// 输出字符串 黑马
1.6使用xhr发起POST请求
// 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.数据交换格式
2.1JSON的两种结构
对象结构:对象结构在 JSON 中表示为 { } 括起来的内容。数据结构为 { key: value, key: value, … } 的键值对结构。其中,key 必须是使用英文的双引号包裹的字符串,value 的数据类型可以是数字、字符串、布尔值、null、数组、对象6种类型。
数组结构:数组结构在 JSON 中表示为 [ ] 括起来的内容。数据结构为 [ "java", "javascript", 30, true … ] 。数组中数据的类型可以是数字、字符串、布尔值、null、数组、对象6种类型。
{ "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 ] ]
2.2JSON和JS对象的互转
从 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"}'
3. 封装自己的Ajax函数
<!-- 1. 导入自定义的ajax函数库 -->
<script src="./itheima.js"></script>
<script>
// 2. 调用自定义的 itheima 函数,发起 Ajax 数据请求
itheima({
method: 'post',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: '水浒传',
author: '施耐庵',
publisher: '北京图书出版社'
},
success: function (res) {
console.log(res)
}
})
</script>
3.1处理data参数
/**
* 处理 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('&')
}
3.2定义itheima函数
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)
}
}
}
3.3判断请求的类型
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)
}
3.4完整代码
function resolveData(data) {
var arr = []
for (var k in data) {
var str = k + '=' + data[k]
arr.push(str)
}
return arr.join('&')
}
// var res = resolveData({ name: 'zs', age: 20 })
// console.log(res)
function itheima(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.XMLHttpRequest Level2的新特性
可以设置 HTTP 请求的时限
可以使用 FormData 对象管理表单数据
可以上传文件
可以获得数据传输的进度信息
5. jQuery高级用法
5.1 jQuery实现文件上传
5.1.1. 定义UI结构
<!-- 导入 jQuery -->
<script src="./lib/jquery.js"></script>
<!-- 文件选择框 -->
<input type="file" id="file1" />
<!-- 上传文件按钮 -->
<button id="btnUpload">上传</button>
5.1.2.验证是否选择了文件
$('#btnUpload').on('click', function() {
// 1. 将 jQuery 对象转化为 DOM 对象,并获取选中的文件列表
var files = $('#file1')[0].files
// 2. 判断是否选择了文件
if (files.length <= 0) {
return alert('请选择图片后再上传!‘)
}
})
5.1.3. 向FormData中追加文件
// 向 FormData 中追加文件
var fd = new FormData()
fd.append('avatar', files[0])
5.1.4. 使用jQuery发起上传文件的请求
$.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)
}
})
5.2 jQuery实现loading效果
5.2.1. ajaxStart(callback)
Ajax 请求开始时,执行 ajaxStart 函数。可以在 ajaxStart 的 callback 中显示 loading 效果
// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
$(document).ajaxStart(function() {
$('#loading').show()
})
注意: $(document).ajaxStart() 函数会监听当前文档内所有的 Ajax 请求。
5.2.2. ajaxStop(callback)
Ajax 请求结束时,执行 ajaxStop 函数。可以在 ajaxStop 的 callback 中隐藏 loading 效果
// 自 jQuery 版本 1.8 起,该方法只能被附加到文档
$(document).ajaxStop(function() {
$('#loading').hide()
})
6. axios
6.1 axios发起GET请求
// 请求的 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)
})
6.2 axios发起POST请求
// 请求的 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)
})
6.3直接使用axios发起请求
6.3.1. 直接使用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)
})
6.3.2. 直接使用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)
})