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);
相关推荐
JYeontu14 小时前
实现一个「曲线滑块验证」功能
前端·javascript·html
IMPYLH15 小时前
HTML 的 <tr> 元素
前端·html
IMPYLH17 小时前
HTML 的 <track> 元素
前端·html
用户298698530142 天前
Python 中 HTML 转 PDF 的实现方法
python·html·api
我就是不信2 天前
用 C 语言实现一个支持 HTML 与视频的 HTTP(S) 服务器
c语言·html·音视频
传人once3 天前
网页文字滚动效果如何做
前端·css·html·jquery·html5
redfred3 天前
HyperFrames 部署教程:5.6 万 Star 开源「写 HTML 出视频」框架,Windows 从零上手(CLI 三条命令 + 7 个避坑)
ffmpeg·开源·自动化·html·音视频
乌暮3 天前
拆解网页的底层逻辑:用费曼学习法讲透 HTML 与 CSS
前端·css·学习·html
传人once3 天前
多图片上传预览功能如何写
前端·css·html·jquery·html5
Da Da 泓4 天前
HTML浅浅入门
前端·html