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);
相关推荐
前端架构师-老李1 天前
HTML与CSS基础第四课—strong、em、b、i 各表示什么
前端·css·html
reasonsummer1 天前
【教学类-07-12】20261028大3班破译电话号码html(手机按钮版本)
python·html
砚凝霜1 天前
CTF Misc 签到 GXUST·CTF:查看源码 + HTML 注释 + Base64 解码(附 Base64 原理)
前端·html
夜雪一千2 天前
标题特殊符号数据清洗实战:解决HTML实体、零宽字符、Emoji乱码踩坑
前端·html
前端架构师-老李2 天前
HTML与CSS基础第二课—初识HTML
前端·css·html
CappuccinoRose2 天前
拖拽交互体系
前端·javascript·css·html·交互·1024程序员节
এ慕ོ冬℘゜2 天前
如何在 HTML 中嵌入音频和视频?
前端·html·音视频
sycmancia3 天前
Qml——Text元素
java·前端·html
西凉的悲伤3 天前
Jsoup 库 HTML 解析详解
java·前端·html·jsoup
inksci4 天前
在线编辑表格,功能强大,json互转
前端·javascript·html