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);
相关推荐
大梦想家a2 小时前
基于 HTML+CSS 的个人生活主页设计与实现
css·html·生活
雪芽蓝域zzs4 小时前
第二十七节:进阶:路由权限控制 + 404 / 401 全局异常页面开发
前端·javascript·html
平头哥技术团队13 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
www_aiyuanma_vip17 小时前
中医文化主题网站源码html源码
html
Z兽兽1 天前
行内块元素在垂直方向上对齐问题
css·html·css3
Wang's Blog1 天前
Vibe Coding一人即团队系列58: HTML演示文稿自动生成
前端·人工智能·html
IMPYLH1 天前
HTML 的 <p> 元素
前端·javascript·html
bjzhang751 天前
使用HTML+CSS美化上传进度条展示
前端·css·html
labixiong2 天前
z-index: 99999 输给 z-index: 2?原生弹窗的 Top Layer 排位战:后进者居上、看得见却点不着
前端·html