正如我们知道的前端ajax请求是以Web Api XMLHttpRequest为核心的。如果不了解ajax和 XMLHttpResquest的同学,点击链接自行了解~
分享一些ajax的另类用法
1. ajax请求文件例子
2. ajax怎么实现下载文件?
3. ajax跨域请求中的options请求是什么情况?
ajax请求文件会发生什么?
示例请求图片代码
<!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>
<div id="result"></div>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open("get", "http://localhost:8080/static/shoes.jpg");
xhr.responseType = "blob"; //告知浏览器返回值的类型,具体查看文档
xhr.onreadystatechange = () => {
if (xhr.readyState === 2) {
var headerO = xhr.getResponseHeader("Content-Length");
console.log(headerO)
}
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.response)
let reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onload = function (e) {
var img = document.createElement("img");
img.src = e.target.result;
document.body.appendChild(img);
}
}
}
}
xhr.send();
</script>
</body>
</html>
当不使用 xhr.responseType = “blob”; 告知浏览器返回值类型是,浏览器会默认放回的是字符串,把图片内容当成字符串。
URL请用允许跨域访问的图片,可以看到页面显示一张图片,控制台信息为:
ajax怎么实现下载文件?
tip:这里为了方便使用FileSaver.js ,具体用法自行查看
代码如下
<!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>
<div id="result"></div>
<body>
<script src="./FileSaver.js"></script>
<script>
var xhr = new XMLHttpRequest();
xhr.open("get", "http://localhost:8080/static/shoes.jpg");
xhr.responseType = "blob";
xhr.onreadystatechange = () => {
if (xhr.readyState === 2) {
var headerO = xhr.getResponseHeader("Content-Length");
console.log(headerO)
}
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.response)
saveAs(xhr.response, "pretty image.png");
}
}
}
xhr.send();
</script>
</body>
</html>
结果下载文件成功。
ajax跨域请求中的options请求是什么情况?
这里分享一个MDN链接了,上面已经写的很好了。
欢迎交流~