HTML加入一些内容方便看效果和做交互:
<div>
<p>当前传输进度:<span id="progress">0%</span></p>
<button id="send">发送</button>
<button id="btn">中断</button>
</div>
JavaScript 核心代码:
// 发送请求
document.getElementById('send').addEventListener('click', function () {
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:9001/test')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
// 获取进度
xhr.addEventListener('progress', function (e) {
console.log(e)
const percent = (e.loaded / e.total) * 100
document.getElementById('progress').textContent = percent.toFixed(2) + '%'
})
// 点击按钮中断请求
document.getElementById('btn').addEventListener('click', function () {
console.log('中断请求')
xhr.abort()
})
xhr.send()
})
这里我自己弄了个简单的node服务器做测试:
const express = require('express')
const app = express()
//创建get请求
app.get('/test', (req, res) => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.setHeader('Access-Control-Allow-Origin', '*')
// 读取txt文件
const fs = require('fs')
const data = fs.readFileSync('resData.txt', 'utf-8')
res.json({
code: 200,
message: "请求成功",
data
})
})
//端口号9001
app.listen(9001)
console.log('server is running at http://localhost:9001')
这里resData.txt是要返回的文本内容,因为要数据凉够大才方便查看进度,所以用了文本文件
效果: