目录
XMLHttpRequest[Level2]:
在第一代XMLHttpRequest中我们智能传输文字信息,文件无法传入。而LV2有一些新特性:
设置HTTP请求的时限:
示例代码:
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.timeout=30
xhr.ontimeout=function () {
console.log('Time Out')
}
FormData对象:
文件上传:
代码示例:
<input type="file" name="file1" id="file1">
<button id="btnUpload">Upload</button>
<br>
<img src="" alt="" id="img" width="800">
<script>
let btn=document.querySelector('#btnUpload')
btn.addEventListener('click',function () {
let file=document.querySelector('#file1').files
if(file.length<=0){
console.log('Please upload files!')
}else{
console.log(file)
}
})
</script>
代码输出:
xhr上传文件请求:
此处使用到BS的进度条样式。
JQ的文件上传:
实现原理代码:
实际代码:
//jQ文件上传方法
let fd=new FormData()
$('#btnUpload').on('click',()=>{
let getfile=$('#file1')[0].files
if(getfile.length<=0){
console.log('Please upload file!')
}else{
//实例化formdata,用于遍历所有表单元素,很方便
fd.append('avatar',getfile[0])
console.log(fd)
$.ajax({
type:'POST',
url:'http://www.liulongbin.top:3006/api/upload/avatar',
data:fd,
contentType:false,
processData:false,
success:res=>{
console.log(res)
}
})
}
})
实现loading效果:
当然我们也有ajax结束的代码。
实际代码演示:
$(document).ajaxStart(function () {
$('#imgInfo').toggleClass('hide')
})
$(document).ajaxComplete(function () {
$('#imgInfo').toggleClass('hide')
})