1. xhr的基本使用
- 使用xhr发起get请求
let xhr = new XMLHttpRequest()
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
- xhr的readyState属性,用来表示当前Ajax请求所处的状态。4表示Ajax请求完成
- 查询字符串:指在url的末尾加上用于向服务器发送信息的字符串(变量)。多个参数使用&分隔
- 使用xhr发起post请求
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('bookname=剑来&author=烽火戏诸侯&publisher=lz')
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
2. url编码
- 概念:url地址不允许出现非英文字符,所以需要将其他字符编码为英文字符
- 编码与解码方法:浏览器提供了url编码与解码的api。encodeURL()编码函数,decodeURL解码函数
3. 数据交换格式
- xml
- json:全称:JavaScript Object Notation,即JavaScript对象表示法。
- json就是JavaScript对象和数组的字符串表示法,本质是字符串
- 作用:json是一种轻量级的文本数据交换格式,用于传输数据,比xml更小,更快,更易解析。
- json语法注意事项:(1)属性名和字符串必须使用双引号包裹(2)json中不能写注释(3)json最外层必须是对象或数组格式(4)不能使用undefined和函数作为json的值
- json与js对象的转换:JSON.parse()==json转js对象(反序列化),JSON.stringify()==js转json(序列化)
4. 封装Ajax函数
function selectData(data) {
const arr = []
for(let k in data) {
arr.push(k + '=' + data[k])
}
str = arr.join('&')
return str
}
function lz(obj) {
const xhr = new XMLHttpRequest()
let qs = selectData(obj.data)
if(obj.method === 'GET') {
xhr.open('GET',obj.url + '?' + qs)
xhr.send()
}else if(obj.method === 'POST'){
xhr.open('POST',obj.url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
let result = JSON.parse(xhr.responseText)
obj.success(result)
}
}
}
5. xhr level2新特性
- 可以设置http请求时限
xhr.timeout = 30
xhr.ontimeout = function() {
console.log('请求超时')
}
- FormData对象管理表单数据
const fd = new FormData()
fd.append('bookname','剑来')
fd.append('author','烽火戏诸侯')
fd.append('publisher','lz')
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(fd)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
- 上传文件
<input type="file" id="file1" />
<button id="btnUpload">上传文件</button>
<br />
<img src="" alt="" id="img" width="800" />
<script>
const btnUpload = document.querySelector('#btnUpload')
btnUpload.addEventListener('click', function() {
const files = document.querySelector('#file1').files
if(files.length <= 0) {
return alert('请选择要上传的文件')
}
const fd = new FormData()
fd.append('avatar',files[0])
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
xhr.send(fd)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
const str = JSON.parse(xhr.responseText)
if(str.status === 200) {
document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + str.url
}else{
console.log('上传失败')
}
}
}
})
</script>
- 显示文件上传进度
xhr.upload.onprogress = function(e) {
if(e.lengthComputable) {
let count = Math.ceil((e.loaded / e.total) * 100)
console.log(count)
}
}
6. axios
- 概念:axios是专注于网络数据请求的js库,相比于原生xhr更简单易用,相比于jQuery更轻量化。
- axios发起请求
<button id="btn1">发起GET请求</button>
<button id="btn2">发起POST请求</button>
<button id="btn3">直接使用axios发起GET请求</button>
<button id="btn4">直接使用axios发起POST请求</button>
<script>
document.querySelector('#btn1').addEventListener('click', function() {
const url = 'http://www.liulongbin.top:3006/api/get'
const paramsObj = {name:'lz',age:20}
axios.get(url,{params : paramsObj}).then(function(res) {
const result = res.data
console.log(result)
console.log(res)
})
})
document.querySelector('#btn2').addEventListener('click', function() {
const url = 'http://www.liulongbin.top:3006/api/post'
const dataObj = {location:'lz',address:20}
axios.post(url,dataObj).then(function(res) {
const result = res.data
console.log(result)
console.log(res)
})
})
axios({
method: 'GET/POST',
url: '',
data: {post参数},
params:get参数,
}).then(function() {})
</script>