form表单提交前设置请求头request header及文件下载

**需求:**想要在form表单submit之前,设置一下请求头。

除了用Ajax发起请求之外,还可以使用FormData来实现,咱不懂就问。

**1 问:**FormData什么时间出现的?与ajax什么联系?

**2 问:**FormData使用方法

参考示例:

html 复制代码
<form id="testForm">
    <input name="username" />
</form>

js:

javascript 复制代码
let data= new FormData(document.getElementById('testForm'));
let xhrObj = new XMLHttpRequest();
xhrObj.open('POST', url, true);
xhrObj.setRequestHeader('自定义请求头', '值');
xhrObj.onload = function () {
    if (xhrObj.readyState === 4 && xhrObj.status === 200) {
        console.log(xhrObj.responseText);
    } else {
        // 请求错误
    }
};
xhrObj.send(data);

如果请求是一个下载文件(二进制流)的url,除了需要额外设置下responseType之外,还需要添加模拟触发下载的代码:

javascript 复制代码
let data= new FormData(document.getElementById('testForm'));
let xhrObj = new XMLHttpRequest();
xhrObj.open('POST', downloadUrl, true);
xhrObj.setRequestHeader('自定义请求头', '值');
xhrObj.responseType = 'blob';
xhrObj.onload = function () {
    if (xhrObj.readyState === 4 && xhrObj.status === 200) {
		let content= xhrObj.getResponseHeader('Content-Disposition');
		let fileName = content.split(';')[1];
		fileName = decodeURI(fileName.split('=')[1]);
		let respObj= xhrObj.response;
		let downloadLink = document.createElement('a');
		downloadLink.href = URL.createObjectURL(respObj);
		downloadLink.download = fileName;
		downloadLink.click();
    } else {
        // 请求错误
    }
};
xhrObj.send(data);
相关推荐
2501_918126919 分钟前
小圆点踢足球
css·html·css3
dsyyyyy110144 分钟前
只用HTML和CSS实现换一换效果
前端·css·html
web打印社区3 小时前
前端html转换pdf并静默打印pdf最佳实现路径
前端·javascript·vue.js·electron·html
Dontla3 小时前
HTML实体转义(HTML Entity Escaping)介绍
前端·html
佛山个人技术开发18 小时前
个人建站接单|汽车汽配行业宽屏自适应官网模板 工厂企业定制建站源码
前端·css·前端框架·html·汽车·php
AIkk861 天前
班级群学习资料分享指南:工具推荐与实践
大数据·人工智能·html
加点油。。。。1 天前
【1.Obsidian渲染html文件】
前端·html·obsidian
程序员小羊!1 天前
01HTML预备知识
前端·html
码农阿豪2 天前
腾讯云COS如何统一设置Content-Disposition为inline:完整指南
cos·inline·header
a1117762 天前
粒子化系统(3D-Particles)THreeJS react
前端·html·jetson